【问题标题】:Mongoose increment value in updateMany operation result NaNupdateMany 操作结果中的 Mongoose 增量值 NaN
【发布时间】:2020-07-09 23:15:18
【问题描述】:

我有以下猫鼬模式:

var AccountSchema = new Schema({
  amount: { type: Number, default: 0 },
  createdAt  : {type : Date, default : Date.now},
  owner: {type : Schema.Types.ObjectId, ref : 'User'},
  environment: {type : Schema.Types.ObjectId, ref : 'Environment'},
  investments: [{
    amount: { type: Number, default: 0 },
    roi: { type: Number, default: 0 },
    createdAt  : {type : Date, default : Date.now},
    code: {type : Schema.Types.ObjectId, ref : 'Code'}
  }]
});

我想对所有具有特定投资代码的对象执行更新操作。 我想以投资完成的 2 倍增加账户金额。

类似的东西:

db.accounts.updateMany({'investments.code':ObjectId("5e7f2a3e20739d171884528f")}, 
{ $inc: { "amount": 'investments.$.amount' * 2 } }
);

结果是记录被更新,但 account 等于 NaN。 我试图通过这样做将所有转换为整数,但它不起作用:

{ $convert: { input: "amount", to: "int" } }

我想更新根文档中的金额字段。 这是一个例子:

假设我有这个帐户:

  amount: 300,
  createdAt  : 12-01-2020,
  owner: "5e7f2a3e20739d1718845256",
  environment: "5e7f2a3e20739d1718845432",
  investments: [{
    amount: 40,
    roi: 0,
    createdAt  : 12-01-2020,
    code: "3"
  },
  {
    amount: 10,
    roi: 0,
    createdAt  : 13-01-2020,
    code: "3"
  }]

我想查找代码 3 的所有投资并增加 300 的金额,每次投资的两倍,在这种情况下 40*2 和 10*2,结果将是 400 (300 + 80 + 20) .

我怎样才能做到这一点?

谢谢

【问题讨论】:

  • 您要更新哪个金额字段?根中的那个还是投资数组中的那个?如果您可以通过示例文档和预期输出来解释,那就太好了。
  • 谢谢,我添加了一个例子。我要增加根文件。

标签: mongodb mongoose mean


【解决方案1】:

最后我改变了更新这些文档的策略(而不是使用 updateMany 来使用 find 和 forEach 子句)并且我做到了:

db.accounts.find(  
{'investments.code':ObjectId("5e7f2a3e20739d171884528f")}).forEach(function (account) {
    account.investments.forEach(function (invest) {
        account.amount = account.amount + (invest.amount * 2) ;
    });
    db.accounts.save(account);
 });

而且效果很好!

谢谢。

【讨论】:

    猜你喜欢
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2015-09-27
    • 2021-09-03
    • 2015-06-11
    相关资源
    最近更新 更多