猫鼬:如何仅使用请求正文中的字段更新嵌套字段?

时间:2018-07-10 14:23:35

标签: node.js mongodb mongoose

希望更新lookupSchema 图像嵌套字段

var lookupSchema = new Schema({
    images:{
      "img1":String,
      "img2":String,
      "img3":String,
      "img4":String
    }
 }

由于我不知道在 findOneAndUpdate 操作期间请求正文中哪些字段可用,所以我无法像这样分配

$set: { 
    'images.img1':  req.body.img1, 
    'images.img2':  req.body.img2,
    'images.img3':  req.body.img3
}

如果我像上面那样编码并指定所有字段,则由于请求中的不可用字段,在更新之后,已经可用的字段将变为空。

需要这样的内容来更新可用字段

$set: { "images.$[element]" : req.body  } 

我进行了很多搜索,但找不到解决方案。

1 个答案:

答案 0 :(得分:1)

您可以简单地创建如下所示的函数来实现您的结果。

function update() {
   let temp = {};
   for(let field in req.body) {
   temp["images."+field] = req.body[field];
   }

  db.collection.findOneAndUpdate({._id:...},{$set:temp},{upsert:true},function(err,result)
  {...});
  }