Douglas Botello Douglas Botello - 4 months ago 9
Node.js Question

Mongoose .save function doesn't appear to be getting called in node.js script

I'm a beginner to node.js and mongoose and full-stack web development in general. I've been beating my head over getting a database set up and communicating with my server and can't quite get it to work. I've been loosely following this tutorial: Easily Develop Node.js and MongoDB Apps with Mongoose

Anyways, my files are organized pretty simply at the moment. My server.js is in the same directory as the "models" folder, which contains my "testSchema.js" file.

I have a script which can be called by the press of a button in my server.js file.

var mongoose = require('mongoose');
var mongoURL = "mongodb://username:password@localhost:27017/test";
mongoose.connect(mongoURL);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("We have connected");
var Item = require("./models/testSchema");
var newItem = Item({
name: 'Peter',
score: 5
});
newItem.save(function(err) {
if (err) throw err;
console.log("Item Created");
});

});
mongoose.connection.close();


This should add a sample document into my model.
And finally, testSchema.js:

var Schema = mongoose.Schema;
var ItemSchema = new mongoose.Schema({
name: {
type: String,
index: true
},
score : Number
});

var Item = mongoose.model('Item', ItemSchema);

module.exports = Item;


So, when I run the script, I get the message "We have connected!", but not the message "Item created", nor any error log which would come after the .save function is called. It would seem this is just getting skipped over, but I have no clue how mongoose and node.js behave in this context. Is .save even getting called?

Additionally: My mongoDB database is hosted on Openshift, but I have been port forwarding to localhost, and it looks like it is working fine. I get the message "Handling connection for 27017" whenever I call the script.

Any help would be greatly appreciated!

** edit **

I can't comment so I'll just edit my post.

Zachary Jacobi and Robert Klep's answers did the trick! Thank you so much, I had no idea node was asynchronous like that.

Answer

Node is asynchronous on I/O, so things won't necessarily happen in the order they appear in your code.

Here the database connection gets opened and node moves on to the next statement without waiting for the rest of the stuff in the callback to get done. So mongoose.connection.close(); is actually executed before newItem.save(function(err) {... is.

To fix this, try:

var mongoose = require('mongoose');
var mongoURL = "mongodb://username:password@localhost:27017/test";
mongoose.connect(mongoURL);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
    console.log("We have connected");
    var Item = require("./models/testSchema");
    var newItem = Item({
        name: 'Peter',
        score: 5
    });
    newItem.save(function(err) {
        if (err) throw err;
        console.log("Item Created");
        mongoose.connection.close();
    });

});