简体   繁体   English

使用 mongoose 增加 mongodb 文档中属性的值

[英]Increment value of a property inside mongodb document using mongoose

So I have this array of objects called "items":所以我有这个称为“项目”的对象数组:

大批

and for each object, I want to find the same object in mongodb using the "baseId" in the Base Document, and then update the "jumlahTerjual" amount by +1, this is the "Base Document":对于每个对象,我想使用基础文档中的“baseId”在mongodb中找到相同的对象,然后将“jumlahTerjual”数量更新+1,这就是“基础文档”: 在此处输入图片说明

I've tried this method but got an error called "jumlahTerjual is not defined":我已经尝试过这种方法,但得到了一个名为“jumlahTerjual 未定义”的错误: 在此处输入图片说明

How can I update it using findByIdAndUpdate correctly?如何正确使用 findByIdAndUpdate 更新它? Any answer will be so much appreciated.任何答案将不胜感激。

Assuming the jumlahTerjual key exists for each object in you base document, when you want to increment it (by any custom value), try:假设基础文档中的每个对象都存在jumlahTerjual键,当您想要增加它(通过任何自定义值)时,请尝试:

items.map(item => {
  return Base.findByIdAndUpdate(item.baseId, {$inc: { jumlahTerjual: 1 }}, function(error, counter) {
    if(error)
      return next(error);
    doc.testvalue = counter.seq;
    next();
  })
})

Use the $inc operator instead of { jumlahTerjual: jumlahTerjual + 1 } as the update object.使用$inc运算符而不是{ jumlahTerjual: jumlahTerjual + 1 }作为更新对象。 Because, currently the interpreter tries to find a local variable called jumlahTerjual which is being incremented by 1 and being assigned to the key in the object found by mongoose.因为,当前解释器试图找到一个名为jumlahTerjual的局部变量,该变量递增 1 并分配给jumlahTerjual找到的对象中的键。 Because we haven't defined a local variable for jumlahTerjual that is why you get the undefined error.因为我们还没有为jumlahTerjual定义局部变量,这就是为什么您会收到未定义错误的原因。

Because you only want to increment, instead of changing the value in the mongoDB record with a new value just use the $inc operator.因为您只想增加,而不是使用新值更改 mongoDB 记录中的值,只需使用$inc运算符。

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

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