Can i get model.save() to have a return value?

1.4k Views Asked by At

I'm new to node and I'm trying to save something to mongo via mongoose. I want to return false if save has an error(eg. there is a user with the current name). The problem is the order of the console.logs 1:2:6:7:3:4:5 is there a way I can call adduser synchronously?

module.exports.addUser = function(username,password){
console.log(1);
var newUser = User({
    username:username,
    password:password
});
console.log(2);
 newUser.save(function(err,prod,numeffect){
    if (err){

        console.log(err);
    }
    if (numeffect === 1){
        console.log(3);
         console.log("num effect = "+numeffect);

    }
    console.log(4);
    console.log(prod);

}).then(function(doc){console.log(5)});
console.log(6);
}

mongoose.addUser(req.body.username,req.body.password);
    console.log(7);
2

There are 2 best solutions below

0
On BEST ANSWER

You should not do them synchronously, or you'll block your whole Node thread.

Instead, what you should be doing is to return a promise, or a simple function with callback. (like mongoose saving one, notice that mongoose supports both)

You can do return newUser.save()

Then you'd run it like addUser.then(). Also, you can drop your module.exports = function() and do module.exports your function with callback or promise.

0
On

NodeJs is single threaded process, and you should not block it with synchronous calls.

You should pass a callback function to perform any actions when you receive a response from mongodb.

That's a significant switch from call and block to callback, when coming into NodeJs.