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

Scheme:

var Post = mongoose.Schema({
        title:       String,
        comments:    [{user: Number, text: String}]
    });

the 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 this a suitable code?

Will it be executed save()after push()?

Will I get the right one newCount?

+3
source share
1 answer

I think it depends on how frequent comments are added to your post.

If this is very common, then you might want to get the last number of comments that would be in your save callback as follows:

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

, push() Mongoose. , $push , $set ( nonAtomicPush). , / , , comment.length n + 1

, . . ,

+4

All Articles