$ set operator mongo删除不存在的密钥?

时间:2017-10-12 08:25:31

标签: mongodb

当我运行此命令时:

.all {
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.container {
  display: flex;
  flex: 1;
  align-items: center;
}

.input {
  flex: 1
}

.label {
  flex: 1;
  background: yellow;
  text-align: right;
  padding-right: 10px;
  margin-bottom: 0;
}

.no-padding {
  padding: 0;
}

var news = { _id: req.body.newsItemId, images: { _id: new ObjectId(), src: result } } Shop.findOneAndUpdate({ _id: ObjectId(req.body.shopId), 'news._id': ObjectId(req.body.newsItemId)}, {"$set": { "news.$": news } }).exec(function(err, shop){ console.log(err, shop); }) 对象中的非现有字段会被空值覆盖,因此会从文档中删除它们。

新闻是来自商店的子文档。所以文档看起来像:

news

运行上面的命令后,新闻只包含一个id和一个图像。我只想覆盖图像数组并保留其他属性。我只使用了集合中的图片来尝试它,但后来我收到了这个错误Mongoose update 'cannot use the part (..) to traverse the element,这就是$来自的地方。

1 个答案:

答案 0 :(得分:0)

通过将代码更改为:

解决了这个问题
var images = [{
    src: result
}]


Shop.findOneAndUpdate({
    _id: ObjectId(req.body.shopId), 
    'news._id':  ObjectId(req.body.newsItemId)},
    {"$set": {
        "news.$.images" : images 
    }
    }).exec(function(err, shop){
        console.log(err, shop);
        return res.status(200).json({message: 'OK'});
    })

所以现在只覆盖图像对象,这就是我想要的。