rishubk rishubk - 3 months ago 8
Node.js Question

Save and Find with Mongoose

I am building a mean stack application. This is one of the functions in my controller.

module.exports.postSuck = function(req, res){
var suck = new Suck(req.body, false);
console.log(req.body)
suck.save(function(err){
if(err){
console.log(err)
}
else{
console.log("saved");
}
});

Suck.find({})
.sort({date: -1})
.exec(function(err, allSucks){
if(err){
res.error(err);
} else {
res.json(allSucks);
}
console.log("found");
});


};

I log to the console "saved" and "found" when each event happens. It always prints "saved" after "found" even though the save function is earlier in the code. Why is this the case? I'm guessing it has something to do with it being asynchronous, but does anyone know how to fix this?

Answer

You can put the .find() function inside the else-statement for the .save() function. This will help you so the .find() function will trigger when the .save() function is done. With the old code the functions were called at the same time and .find() was a bit faster to finish.

module.exports.postSuck = function(req, res){
    var suck = new Suck(req.body, false);
    console.log(req.body)
    suck.save(function(err){
        if(err){
            console.log(err)
        }
        else{
            console.log("saved");
            Suck.find({})
                .sort({date: -1})
                .exec(function(err, allSucks){
                    if(err){
                        res.error(err);
                    } else {
                        res.json(allSucks);
                    }
                    console.log("found");
                })}})};

Hope this helps you! Good luck!

Comments