Mongoose,MongoDB:如何在push()之后保存()文档? [英] Mongoose, MongoDB: How to save() document after push()?

查看:52
本文介绍了Mongoose,MongoDB:如何在push()之后保存()文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模式:

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

代码:

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) {
    ...
  });

这是合适的代码吗?

save()是否将在push()之后执行?

我会得到正确的newCount吗?

推荐答案

我认为这取决于将评论添加到您的帖子中的频率

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
});

请记住,push()在Mongoose中是原子的.换句话说,它使用 $ push 而不是 $ set (与

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

这篇关于Mongoose,MongoDB:如何在push()之后保存()文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆