仅更新猫鼬中已更改的字段

时间:2019-01-31 09:48:09

标签: express mongoose

我正在尝试使用ExpressJS和Mongoose更新子文档。但是仅更改的字段。但是它会以某种方式更新所有必要的字段,而且还会更新不需要更改的字段。

这是ExpressJS中的Update函数:

postController.updateMessage = function(req, res, item) {
  var id = req.body.id;
  var saveData = {
    title: req.body.title,
    text: req.body.text,
    title_double: req.body.title_double,
    text_double: req.body.text_double
  };
  item.findOneAndUpdate({'subitem.messages._id': id}, {$set:{'subitem.$.messages': saveData}}, {upsert: true, new: true},(error, result) => {
    console.log(result);
    console.log(error);
  });
};

这是猫鼬模型:

var submessages = mongoose.Schema({
  date: String,
  type: String,
  title: String,
  text: String,
  title_double: String,
  text_double: String
});

var subitems = new mongoose.Schema({
  title: String,
  messages: [submessages]
});

var menuItems = new mongoose.Schema({
  title : String,
  subitem: [subitems]
}, {collection: 'menu_items'});

module.exports = mongoose.model("menu_items", menuItems);

1 个答案:

答案 0 :(得分:0)

您有两个嵌套数组,而您是对一个数组的检查/条件

{$set:{'subitem.$.messages.$': saveData}}

类似的情况