gpt4 book ai didi

node.js - 如何使用 Node.Js 在 MongoDB 中插入或更新数组?

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:28 24 4
gpt4 key购买 nike

我有一个 products 集合,其中一些产品具有以下结构:

{
_id: anID
shops:
[
{
_id : shopId,
price: productsPrice
},
...
]
}

我想更新给定产品和商店的价格,但如果数组中不存在,则插入该商店及其价格。

我是 MongoDB 的初学者。使用 Node.Js/express(mongoDB 驱动程序),但不使用 mongoose。

提前致谢

最佳答案

您可以尝试.bulkWrite() - 这将推送新的商店对象或更新现有的:

var inputObj = { "_id": anShopID, "price": someValue }
db.collection.bulkWrite([{
updateOne: {
"filter": { "_id": anID, "shops._id": inputObj._id },
"update": { $set: { "shops.$.price": inputObj.price } }
}
}, {
updateOne: {
"filter": { "_id": anID, "shops._id": { $ne: inputObj._id } },
"update": { $push: { "shops": inputObj } }
}
}])

关于node.js - 如何使用 Node.Js 在 MongoDB 中插入或更新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59846498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com