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