我想更新模式数组内的对象,而不必向数据库发出两个请求。如果对象已经存在并且工作正常,我目前正在使用 findOneAndUpdate() 增加字段。但如果该对象不存在,那么我必须使用 update() 发出另一个请求来推送新对象并使其可用于以后的增量。
我希望能够只执行一个请求(例如 findOne())来获取用户,然后仅当数组中存在对象时才增加字段,如果不存在,我想推送新对象。然后保存文档。这样我只从数据库发出一次读取/请求,而不是两次。
这是现在的功能:
async addItemToCart(body, userId) {
const itemInDb = await Model.findOneAndUpdate(
{
_id: userId,
'cart.productId': body.productId,
},
{ $inc: { 'cart.$.count': 1 } }
);
if (itemInDb) return true;
const updated = await Model.update(
{ _id: userId },
{ $push: { cart: body } }
);
if (updated.ok !== 1)
return createError(500, 'something went wrong in userService');
return true;
}
我想做的是:
async addItemToCart(body, userId) {
const itemInDb = await Model.findOne(
{
_id: userId,
'cart.productId': body.productId,
}
);
if (itemInDb) {
/**
*
* increment cart in itemInDb then do itemInDb.save() <<------------
*/
} else {
/**
* push product to itemInDb then save
*/
}
谢谢!
最佳答案
您可以尝试使用 upsert
来使用 findOneAndUpdate
。
upsert: true
then create data if not exists in DB.
Model.findOneAndUpdate(
{
_id: userId,
'cart.productId': body.productId,
},
{ $inc: { 'cart.$.count': 1 } },
{
upsert: true,
}
)
在一个查询中使用 $set
和 $inc
。
try {
db.scores.findOneAndUpdate(
{
_id: userId,
'cart.productId': body.productId,
},
{ $set: { "cart.$.productName" : "A.B.C", "cart.$.productPrice" : 5}, $inc : { "cart.$.count" : 1 } },
{ upsert:true, returnNewDocument : true }
);
}
catch (e){
//error
}
引用链接:here
关于javascript - 在找到对象数组(使用 findOne())之后和保存之前如何增加对象数组中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52772181/