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) {
...
});
它是合适的代码吗?
是否save()
将在之后执行push()
?
我会得到正确的吗newCount
?
我认为这取决于您的帖子中添加评论的频率
如果非常频繁,那么您可能需要获取最新的评论计数,这将在您的保存回调中,如下所示:
myPost.comments.push({user: 42, text: 'blablabla'});
myPost.save(function (err, post) {
newCount = post.comments.length
});
请记住,push() 在 Mongoose 中是原子的。换句话说,它使用$push http://docs.mongodb.org/manual/reference/operator/update/push/在引擎盖下而不是$set http://docs.mongodb.org/manual/reference/operator/update/set/(对比非原子推送 http://mongoosejs.com/docs/api.html#types_array_MongooseArray-nonAtomicPush)。因此,理论上,任何数量的其他推送/保存评论都可以同时发生,这意味着在您给定的示例中,comments.length 不一定是 n+1
如果您不希望收到很多评论,那么您的示例就足够了。它有时可能不太准确。好处是它会快一点,因为检索计数将是同步的
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)