node.js - Updating multiple sub-documents via Mongoose? -


say example, we're using following schema define comments tree;

{     "_id" : objectid("id_here"),     "parentcomment" : "this opinion",     "ishidden" : false,     "comments" : [          {             "comment" : "i disagree opinion",             "ishidden" : false         },          {             "comment" : "test post",             "ishidden" : false         },          .... } 

so, if update parent comment set ishidden flag true banned phrases, we'd this;

        var usercomments = require('mongoose').model("usercomments");         (let = 0; < bannedphrases.length; i++) {             var conditions = { parentcomment: bannedphrases[i] }                 , update = { ishidden: true}                 , options = { multi: true };              usercomments.update(conditions, update, options, callback);         } 

now, consider subdocument "comments" (threaded comments, multiple entries) - how able go updating these?

the solution can think of update nested document 1 one.

assume we've got hold of banned phrases, array of strings:

var bannedphrases = ["censorship", "evil"]; // , more ... 

then perform query find usercomments has comments contain of bannedphrases.

usercomments.find({"comments.comment": {$in: bannedphrases }}); 

by using promises, can perform update asynchronously together:

usercomments.find({"comments.comment": {$in: bannedphrases }}, {"comments.comment": 1})   .then(function(results){     return results.map(function(usercomment){         usercomment.comments.foreach(function(commentcontainer){          // check if comment contains banned phrases          if(bannedphrases.indexof(commentcontainer.comment) >= 0) {            commentcontainer.ishidden = true;          }        });         return usercomment.save();     });   }).then(function(promises){      // step may vary depending on promise library using      return promise.all(promises);    }); 

if use bluebird js mongoose's promise library, code simplified:

usercomments.find({"comments.comment": {$in: bannedphrases}}, {"comments.comment": 1})     .exec()     .map(function (usercomment) {          usercomment.comments.foreach(function (commentcontainer) {             // check if comment contains banned phrases             if (bannedphrases.indexof(commentcontainer.comment) >= 0) {                 commentcontainer.ishidden = true;             }         });          return usercomment.save();     }).then(function () {     // done saving }); 

Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

android - CoordinatorLayout, FAB and container layout conflict -