我似乎无法在mongoose中增加嵌套值。我尝试过多次在网上找到的修订,似乎都没有。我使用的是mongodb 3.2和mongoose 4.9.5。
这个项目是一个论坛。有一个带有“posts”属性的线程是一个数组。每个帖子都有一个“喜欢”的属性,每个喜欢该帖子的人都有一个“用户”属性,以及一个应该随每次更新而递增的计数属性。这是我的模特:
const threadSchema = mongoose.Schema({
title: {type: String, required: true},
date: {type: Date, default: Date.now},
author: {type: String, required: true},
content: {type: String},
posts: [{
content: {type: String, required: true},
user: {type: String, required: true},
created: {type: Date, default: Date.now},
likes: {
users: [String],
count: {type: Number, default: 0}
},
comments: [{
comment: {type: String},
user: {type: String},
created: {type: Date, default: Date.now},
likes: {type: Number, default: 0}
}]
}]
});
这是我的更新代码。它推动posts.likes.users数组很好,但不会增加:
Threads.findOneAndUpdate({"posts._id": req.body.postId}, {"$push": {"posts.$.likes.users": user}}, {$inc: {"posts.$.likes.count": 1}})
我也试过这些版本:
{"$inc": {"posts.likes.count": 1}}
{"$inc": {"posts.$.likes.count": 1}}
{"$inc": {"posts.$.likes.$.count": 1}}
感谢。
答案 0 :(得分:1)
好像我不能在同一行中进行两次编辑。将它们分开似乎可以解决问题。
Threads.findOneAndUpdate({"posts._id": req.body.postId},
{"$push": {"posts.$.likes.users": user}})
.exec()
.then((post) => {
//some stuff
})
Threads.findOneAndUpdate({"posts._id": req.body.postId},
({"posts._id": req.body.postId},
{$inc: {"posts.$.likes.count": 1}})
.exec()
.then((post) => {
// some other stuff
})