javascript - 在找到对象数组(使用 findOne())之后和保存之前如何增加对象数组中的字段?

标签 javascript node.js mongodb mongoose nosql

我想更新模式数组内的对象,而不必向数据库发出两个请求。如果对象已经存在并且工作正常,我目前正在使用 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/

相关文章:

javascript - 从 Ext.data.Store 扩展不起作用

javascript - 如何使用 Node 从 WebStorm 中的 JavaScript 堆栈跟踪导航到原始 TypeScript 文件?

javascript - 在 Express.js 中从 UInt8Array 发送二进制响应

c# - 在Docker中连接到mongodb

javascript - 在 THREE.js 中使用四元数设置向量的全局旋转

javascript - bxSlider 在调整大小时不显示幻灯片

javascript - 解构回退以防止未定义的错误?

node.js - Multer 不使用 next-connect 返回 req.body 和 req.file

mongodb - Flutter:我可以将Firebase Auth与Mongodb数据库混合吗?

node.js - 仅当 ref 不为空时才尝试填充 Mongoose - 不起作用