Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

519
Views
Best way to use Mongoose to update an Array of Objects?

my req.body is this, its coming from my front end so its a couple objects in an array, id like to update based on the records that are matching but the page has changed.

[
[0]   {
[0]     _id: '60393a58c772c12724aa636e',
[0]     title: 'newTitle2',
[0]     page: '8',
[0]     book: '010',
[0]     __v: 0
[0]   },
[0]   {
[0]     _id: '60394e08f6e0ad0bb077e0bc',
[0]     title: 'newTitle3',
[0]     page: '123',
[0]     book: '099',
[0]     __v: 0
[0]   }
[0] ]

My route is this

router.post("/dataSend", async(req, res) => {

let { title, page, book} = req.body;

console.log(req.body)
const filter = { title };
const update = { page};

let doc = await Data.findOneAndUpdate({title:req.body[0].title},{page: req.body[0].page});

res.send(doc)
})

So this will work if I specifiy with mongoose that I want to update the [0] first array, but I would like to update everything, I am not sure if .map or forEach or a loop is the way to go?

Any ideas

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Rather than calling findOneAndUpdate in a loop, I think bulkWrite (docs) would be the better option in this case, so you don't send your updates to Mongo one by one. You can map your update operations and send them in one batch. Please refer to the following snippet for an example:

router.post("/dataSend", async(req, res) => {
  const records = req.body

  const updateOps = records.map(record => {
    const updateOp = {
      'updateOne': {
        'filter': {
          'title': record.title,
        },
        'update': {
          'page': record.page
        },
      }
    }
    
    return updateOp
  })


  const result = await Data.bulkWrite(updateOps)

  res.send(result)
})

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!