Mongoose to modify a specific value in an array

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.