简体   繁体   English

使用 Mongoose 更新对象数组的最佳方法?

[英]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.我的 req.body 是这样的,它来自我的前端,所以它是一个数组中的几个对象,id 喜欢根据匹配但页面已更改的记录进行更新。

[
[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?因此,如果我使用 mongoose 指定我想更新 [0] 第一个数组,但我想更新所有内容,我不确定是否。

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.在这种情况下,我认为bulkWrite (docs)不是在循环中调用findOneAndUpdate而是更好的选择,因此您不会将更新一一发送到 Mongo。 You can map your update operations and send them in one batch.您可以 map 您的更新操作并分批发送。 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) })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM