Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongoose: Update multiple records with randomly generated data

There is a clients collection which is structured like this:

const ClientSchema = mongoose.Schema({
          name: {
            type: String,
            required: true,
          },
          region: {
            type: String,
            required: true,
          },
          balance: {
            type: Number,
            default: 0,
          },
          phone: {
            type: Number,
            unique: true,
            required: true,
          },
});

and here is the sample data I have stored:

[
  {_id: 'someID1', name: 'Joe Smith', region: 'USA', balance: 0, phone: 123456789},
  {_id: 'someID2', name: 'Kim Laws', region: 'CANADA', balance: 100, phone: 342345345},
  {_id: 'someID3', name: 'Dandy Cruz', region: 'EUROPE', balance: 2000, phone: 4536456456},
]

Data is displayed as a table on the client app, and users can modify the data on the table (something like a spreadsheet).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So suppose, after user messes around with the initial data, it mutated to something like this:

[
  {_id: 'someID1', name: 'Freedom Brights', region: 'AFRICA', balance: 2000, phone: 123456789},
  {_id: 'someID2', name: 'Kim Sun', region: 'ASIA', balance: 0, phone: 342345345},
  {_id: 'someID3', name: 'Dandy Cruz', region: 'EUROPE', balance: 2000, phone: 4536456456},
]

How would you update all these records on a single request with mongoose?

I’ve tried some googling and found methods like update() and updateMany() but all the examples out there doesn’t exactly show how to approach this problem.

I would highly appreciate any help. Thank you!

>Solution :

you can use the bulkwrite

db.collection.bulkWrite( [
   { updateMany :
      {
         "filter" : <document>,
         "update" : <document or pipeline>,          // Changed in MongoDB 4.2
         "upsert" : <boolean>,
         "collation": <document>,                    // Available starting in 3.4
         "arrayFilters": [ <filterdocument1>, ... ], // Available starting in 3.6
         "hint": <document|string>                   // Available starting in 4.2.1
      }
   }
] )

also the document https://mongoosejs.com/docs/api.html#model_Model.bulkWrite

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading