2017-05-13 28 views
0

我似乎無法在貓鼬中增加嵌套值。我已經嘗試了多次修訂,我已經在網上找到了,而且沒有任何修改。我正在使用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

好像我不能在同一行兩者都做編輯。把它們分開似乎有訣竅。

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