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);
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 yourmodule.exports = function()
and domodule.exports
your function withcallback
orpromise
.