我有嵌入文檔(「註釋」)的陣列的文檔,並且看起來像這樣的一個示例:Mongoose - 將嵌入式文檔的數組循環以便向字段集中新的值。
{
"_id" : ObjectId("539e9213209e743d107e7202"),
"article" : "article1",
"comments" : [
{
"comment" : "comment1",
"created" : ISODate("2014-06-16T06:43:38Z"),
"_id" : ObjectId("539e921a209e743d107e7203"),
"read" : {
"marked" : false
},
"timesent" : {
"datetime" : "Mon Jun 16 2014 02:43:38 GMT-0400 (EDT)",
"hour" : 2,
"minute" : "43",
"second" : 38,
"am" : true,
"month" : 5,
"day" : 16,
"year" : 2014
}
}
]
}
對於註釋陣列中的每個評論,是有辦法批更新的字段「read」:{「marked」:true}?
正在與node.js的工作,並在心中是這樣的(可疑的部分,如果(req.body.readComment){..開始
// update the article with this id (accessed by PUT at
// http://localhost:4200/api/v1/articles/:article_id)
.put(function(req, res) {
Article.findById(req.params.article_id, function(err, article) {
if (err)
res.send(err);
if (req.body.comment) {
article.comments.push({
comment : req.body.comment,
timesent :
{
datetime : req.body.datetimeNow,
hour : req.body.hourNow,
minute : req.body.minuteNow,
second : req.body.secondNow,
am : req.body.amNow,
month : req.body.monthNow,
day : req.body.dayNow,
year : req.body.yearNow
},
read :
{
marked : req.body.readComment,
datetime : req.body.readCommentDatetime
},
created : req.body.datetimeNow
});
} // if newComment
if (req.body.readComment) {
var comments = // some sort of .find ?
var embeddedDoc;
for (var i=0, length=comments.length; i < length; i++){
embeddedDoc = comments[i];
embeddedDoc_id = // something to find the embedded doc_id ?
console.log(i);
article.comments.push({ // maybe push to the embedded doc_id
read :
{
marked : req.body.readComment,
datetime : req.body.readCommentDatetime
}
});
};
} // if readComment == true (from ajax .put)
// save the article, and check for errors
article.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Update "' + req.params.article_id });
});
});
})
有沒有答案,不符合你的問題的需要? –
@NeilLunn不一定..數據庫已經發生了一些變化(感謝你的真棒答案),並且還沒有想辦法抓住comments._id,因此還沒有對此進行測試。與往常一樣,答案看起來很理想,所以接受,還是應該先測試它?剛剛投票! – StackThis