简体   繁体   English

猫鼬findOneAndUpdate删除嵌套的变量

[英]mongoose findOneAndUpdate deletes nested vars

In my express/mongoose code when I update a nested var it deletes any other nested vars in the object I didn't update? 在我的express / mongoose代码中,当我更新嵌套var时,它会删除我未更新的对象中的任何其他嵌套vars吗?

My schema: 我的架构:

var MySchema = new Schema({
  active: { type: Boolean, required: true, default: true },
  myvar: {
    useDefault: { type: Boolean, required: true },
    custom: { type: String },
    default: { type: String }
  }
});

My express middleware update function: 我的快速中间件更新功能:

var updateData = req.body;
MySchema.findOneAndUpdate({ active: true }, updateData, function(err, myschema) {
    if (err) throw err;
    if (!myschema) { response(403, { success:false, message: "myschema not updated." }, res); }
    // success
    response(200, { success:true, message: "myschema updated." }, res);
});

The record initially look like this: 记录最初看起来像这样:

{
    "myvar": {
        "useDefault": true,
        "custom": "some custom var",
        "default": "some value"
    }
}

When I submit an update to say the myvar.useDefault value the record ends up like this: 当我提交更新以说myvar.useDefault值时,记录最终如下所示:

{
    "myvar": {
        "useDefault": false
    }
}

Can anyone advise how to update only the targeted var and leave any other vars as they were? 谁能建议如何仅更新目标变量并保留其他变量?

The answer was to convert the response.body object to dot notation and pass that modified object to mongoose findOneAndUpdate. 答案是将response.body对象转换为点表示法,然后将修改后的对象传递给mongoose findOneAndUpdate。 Thanks to @btkostner on Gitter for the answer and his toDot function. 感谢Gitter上的@btkostner提供了答案以及他的toDot函数。 Here is the relevant bits of code: 这是相关的代码位:

function(req, res) {
  // convert response to dot notation so objects retain other values
  var dotData = toDot(req.body, '.');
  MySchema.findOneAndUpdate({ active: true }, dotData, function(err, myschema) {
    ...
}

// author: @btcostner 
function toDot (obj, div, pre) {
  if (typeof obj !== 'object') {
    throw new Error('toDot requires a valid object');
  }
  if (pre != null) {
    pre = pre + div;
  } else {
    pre = '';
  }
  var iteration = {};
  Object.keys(obj).forEach(function(key) {
    if (_.isPlainObject(obj[key])) {
      Object.assign(iteration, _this.toDot(obj[key], div, pre + key));
    } else {
      iteration[pre + key] = obj[key];
    }
  });
  return iteration;
};

NOTE: I had to convert the toDot() function to ES5 for my project, here is the original ES6 version: github.com/elementary/houston/blob/master/src/lib/helpers/dotNotation.js 注意:对于我的项目,我必须将toDot()函数转换为ES5,这是原始ES6版本: github.com/elementary/houston/blob/master/src/lib/helpers/dotNotation.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM