[英]Updating multiple sub-documents via Mongoose?
例如,我們使用以下模式來定義評論樹;
{
"_id" : ObjectId("id_here"),
"parentComment" : "This is my opinion",
"isHidden" : false,
"comments" : [
{
"comment" : "I disagree with your opinion",
"isHidden" : false
},
{
"comment" : "Test Post",
"isHidden" : false
},
....
}
因此,如果我們要更新父評論以將禁用短語的 isHidden 標志設置為 true,我們會這樣做;
var userComments = require('mongoose').model("UserComments");
for (let i = 0; i < bannedPhrases.length; i++) {
var conditions = { parentComment: bannedPhrases[i] }
, update = { isHidden: true}
, options = { multi: true };
userComments.update(conditions, update, options, callback);
}
現在,考慮子文檔“評論”(線程評論、多個條目)——我們如何才能更新這些?
我能想到的解決辦法是將嵌套文檔一一更新。
假設我們已經掌握了被禁止的短語,它是一個字符串數組:
var bannedPhrases = ["censorship", "evil"]; // and more ...
然后,我們執行查詢找到所有UserComments
其中有comments
包含任何的bannedPhrases
。
UserComments.find({"comments.comment": {$in: bannedPhrases }});
通過使用promise,我們可以一起異步執行更新:
UserComments.find({"comments.comment": {$in: bannedPhrases }}, {"comments.comment": 1})
.then(function(results){
return results.map(function(userComment){
userComment.comments.forEach(function(commentContainer){
// Check if this comment contains banned phrases
if(bannedPhrases.indexOf(commentContainer.comment) >= 0) {
commentContainer.isHidden = true;
}
});
return userComment.save();
});
}).then(function(promises){
// This step may vary depending on which promise library you are using
return Promise.all(promises);
});
如果你使用Bluebird JS是 Mongoose 的 promise 庫,代碼可以簡化:
UserComments.find({"comments.comment": {$in: bannedPhrases}}, {"comments.comment": 1})
.exec()
.map(function (userComment) {
userComment.comments.forEach(function (commentContainer) {
// Check if this comment contains banned phrases
if (bannedPhrases.indexOf(commentContainer.comment) >= 0) {
commentContainer.isHidden = true;
}
});
return userComment.save();
}).then(function () {
// Done saving
});
這個鏈接應該有幫助:
https://jira.mongodb.org/browse/SERVER-1243
你可以做的是:
ParentComment.findById(parentCommendId, {'comments.$[].isHidden': true})
用英語來說,這就是說,找到 id 為parentCommendId
的評論,並將其所有子評論的 isHidden 字段設置為 true。
希望這有幫助!
要更新所有子文檔,
db.coll.update({}, {$set: {“a.$[].b”: 2}})
Input: {a: [{b: 0}, {b: 1}]}
Output: {a: [{b: 2}, {b: 2}]}
要僅更新匹配的子文檔,
db.coll.update({"a.b":0}, {$set: {“a.$[i].b”: 2}}, {arrayFilters: [{“i.b”: 0}]})
Input: {a: [{b: 0}, {b: 1}]}
Output: {a: [{b: 2}, {b: 1}]}
有關更新子文檔的更多見解,請參閱此JIRA票證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.