Mongoose, MongoDB: How to save() document after push()?

mongodb, mongoose, node.js

Solution

I think it depends on how frequent comments will be added to your post

If it's very frequent, then you may want to get the latest comment count, which would be in your save callback like so:

myPost.comments.push({user: 42, text: 'blablabla'});
myPost.save(function (err, post) {
    newCount = post.comments.length
});

Remember that push() is atomic in Mongoose. In other words it uses $push under the hood and not $set (contrast with nonAtomicPush). So in theory any number of other pushes/saves to comments can happen concurrently which means that in your given example, comments.length isn't necessarily n+1

If you're not expecting a lot of comments, then your example should suffice. It may be less accurate from time to time. The upside is it will be a little faster as retrieve the count will be synchronous

Problem

Schema: ``` var Post = mongoose.Schema({ title: String, comments: [{user: Number, text: String}] }); ``` Code: ``` oldCount = myPost.comments.length; // for example 'n' myPost.comments.push({user: 42, text: 'blablabla'}); newCount = myPost.comments.length; // should be 'n+1' myPost.save(function (err) { ... }); ``` Is it a suitable code? Whether the `save()` will be executed after `push()`? Will I get the correct `newCount`?

Original source