通过猫鼬更新多个子文档?

Eog*_*han 2 mongoose mongodb node.js

举例来说,我们使用以下模式定义注释树;

{
    "_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
        }, 
        ....
}
Run Code Online (Sandbox Code Playgroud)

因此,如果我们要更新父注释,以将禁止使用的短语的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);
        }
Run Code Online (Sandbox Code Playgroud)

现在,考虑子文档“注释”(线程注释,多个条目)-我们将如何进行更新?

kaz*_*rin 5

我能想到的解决方案是逐个更新嵌套文档。

假设我们掌握了被禁止的短语,它是一个字符串数组:

var bannedPhrases = ["censorship", "evil"]; // and more ...
Run Code Online (Sandbox Code Playgroud)

然后,我们执行查询查找所有UserComments具有comments包含任何的bannedPhrases

UserComments.find({"comments.comment": {$in: bannedPhrases }});
Run Code Online (Sandbox Code Playgroud)

通过使用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); 
  });
Run Code Online (Sandbox Code Playgroud)

如果您使用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
});
Run Code Online (Sandbox Code Playgroud)