MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Aggiornare più documenti secondari tramite Mongoose?

La soluzione che mi viene in mente è aggiornare il documento annidato uno per uno.

Supponiamo di essere in possesso delle frasi vietate, che sono un array di stringhe:

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

Quindi eseguiamo una query per trovare tutti i UserComments che ha comments che contengono una qualsiasi delle bannedPhrases .

UserComments.find({"comments.comment": {$in: bannedPhrases }});

Utilizzando le promesse, possiamo eseguire l'aggiornamento in modo asincrono insieme:

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); 
  });

Se utilizzi Bluebird JS è la libreria delle promesse di Mongoose, il codice potrebbe essere semplificato:

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
});