If a document has a field of type string array, such as {id:1,tags:[' AA ', ' BB ', ' cc '}, now to change the ' BB ' of the tags field to ' bb ', the previous way is to write:
Articlemodel.find ({tags:{$all: [Doc.name]}},function(err,articles) {Articles.foreach (function(article) { for(varj = 0;j<article.tags.length;j++){ if(Article.tags[j] = = =doc.name) {Article.tags[j]=Req.body.name; Article.markmodified (' Tags '); Article.save (); Break; } } }) })
The above code means that the tags field of all documents found in the article collection contains records with Doc.name, and then iterates through the found result set, looping through each record. This code is cumbersome, inefficient, and later found here inspiration http://cnodejs.org/topic/541be549ad60405c1f02f660, the improved code is as follows:
Articlemodel.update ({tags:{$all: [Doc.name]},tags:doc.name, $atomic:true},{$set: {"tags.$": Req.body.name }},{multi:True},function(err) { ifreturn console.log (err); Console.log (' article updated successfully ');})
The following is also possible, I guess the fields that need to be modified are only available in the conditional expression of the first argument .
Articlemodel.update ({tags:{$all: [Doc.name]}, $atomic:true},{$set: {"tags.$": Req.body.name}},{multi: True},function(err) { ifreturn console.log (err); Console.log (' article updated successfully ');})
Mongoose to modify a specific value in an array