【问题标题】:Mongoose/MongoDB: Increment value in a nested arrayMongoose/MongoDB:嵌套数组中的增量值
【发布时间】:2022-02-01 01:04:47
【问题描述】:

假设我有一份投资者名单,对于每个人,我们都会存储他们持有哪些公司的股份以及股份数量:

"investors": [
  {
    "userID": 0,
    "investments": [
      {
        "company": "Google",
        "shares": 3
      },
      {
        "company": "Amazon",
        "shares": 5
      }
    ]
  }
]

所以在这个例子中,ID 为 0 的人拥有 3 股谷歌股票和 5 股亚马逊股票。我正在尝试写一个猫鼬请求,我可以用它来向投资者添加新股,无论它是否是一家新公司。到目前为止,我最好的尝试是这样的:

Investor.updateOne(
  { 0 },
  // newInvestments is an array that contains all new investments that should be added to the database
  { userID: 0, $set: { investments: newInvestments } },
  { upsert: true }
)

这在添加新公司时效果很好,但对于用户已经拥有股份的公司,旧值会被新值覆盖。因此,例如,如果该人再购买 2 股 Google 股票,我们希望他们的股票增加到 5 股,但这样只会被 2 股覆盖。

我相信我想要实现的目标可以使用$inc 来完成,但我无法弄清楚这种特定情况下的语法。我对 MongoDB 还很陌生 - 欢迎提出任何建议。

【问题讨论】:

  • $inc 可能是一个不错的选择。您尝试了哪些$inc 查询,结果如何?
  • 我不知道如何将它合并到我现有的代码中。我的问题是 newInvestments 是一个对象数组,我只需要增加其中的一个特定字段(共享),所以如果我用 $inc 替换 $set,那是行不通的。
  • 更换它是不够的。您需要定位嵌套项目。有多种方式,包括functionaddToSet
  • 我真的很困惑这些的用法,抱歉。我尝试了 "{ userId: 0, $addToSet: {investments: {$inc: newInvestments.shares}}}" 作为我的第二个参数,但它没有用(我也没想到,文档并不是真的详细说明我的用例)。

标签: node.js typescript mongodb mongoose


【解决方案1】:

使用 javascript 会很简单:

  1. 查找文档
  2. 使用js来push新的投资或增加shares如果存在的话
  3. 致电doc.save()
const investor = await Investor.findById(0);
newInvestments.forEach(newInv => {
  const index = investor.investments.findIndex(inv => inv.company === newInv.company);
  if(index === -1) {
    investor.investments.push(newInv);
  } else {
    investor.investments[index].shares += newInv.shares;
  }
});
investor.save()

【讨论】:

    猜你喜欢
    • 2013-04-08
    • 2017-03-15
    • 2020-09-29
    • 2015-01-31
    • 2016-10-14
    • 2013-03-27
    • 2016-02-09
    • 1970-01-01
    相关资源
    最近更新 更多