举例来说,我们使用以下模式来定义评论树;
{
"_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);
});
如果你使用蓝鸟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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)