【问题标题】:MongoDB / Meteor: Multiply entire array within collectionMongoDB / Meteor:在集合中乘以整个数组
【发布时间】:2016-05-10 20:03:12
【问题描述】:

我在 Meteor / MongoDB 中乘以一组键值对时遇到问题。我想将整个成分列表与固定值相乘。集合如下所示:

"ingredients" : [
    {
        "ingredient" : "noodle",
        "amount" : 500,
        "unit" : "g"
    },
    {
        "ingredient" : "cheese",
        "amount" : 100,
        "unit" : "g"
    }
],

现在,我想将 amount 值乘以某个数字 multip,比如说 1,5。所需的输出如下所示:

"ingredients" : [
    {
        "ingredient" : "noodle",
        "amount" : 750,
        "unit" : "g"
    },
    {
        "ingredient" : "cheese",
        "amount" : 150,
        "unit" : "g"
    }
],

现在我有这个:

for (i in this.ingredients){
  var precalc = this.ingredients[i].amount * multip; //Here's the Multiplicator
  var prez=this.ingredients[i].ingredient;
  var prem=this.ingredients[i].unit;
  Recipes.update(
    {"_id": this._id},
    {"$set": {
      "ingredients":[{ingredient:prez, amount:precalc, unit:prem}]
      }}
  );
}

我预先计算了新值并使用了 $set ,因为显然 $mul 运算符不适用于流星。该解决方案部分有效,但不幸的是它会覆盖所有成分并且仅将最后一个成分相乘(这很明显)。必须有一个更简单的方法来做到这一点 - 我只是没有找到它。我是 MongoDB 和 Meteor 的新手,非常感谢任何帮助!

【问题讨论】:

  • 如何在循环之后使用所有成分更新集合(在循环期间收集数组)?

标签: arrays mongodb list meteor


【解决方案1】:

不要对每种成分执行更新,只对整个文档执行更新。我会做这样的事情:

let newIngredients = this.ingredients.map(x => {
  ingredient: x.ingredient,
  amount: x.amount * 1.5,
  unit: x.unit
});

Recipes.update(
  {_id: this._id},
  {$set: {ingredients: newIngredients}}
);

【讨论】:

  • 谢谢!我知道这很容易。不幸的是,胖箭头语法不起作用,但我最终会创建一个 newIngredients 数组并更新一次 Collection。完美运行!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-07
  • 1970-01-01
相关资源
最近更新 更多