繁体   English   中英

猫鼬不保存嵌套对象

[英]Mongoose not saving nested object

我很困惑为什么 Mongoose 没有保存我的对象:

var objectToSave = new ModelToSave({
  _id : req.params.id, 
  Item : customObject.Item //doesn't save with customObject.getItem() neither
});

但是正在保存这个; 如下所示或使用硬编码值:

var objectToSave = new ModelToSave({
  _id : req.params.id, 
  Item : {
    SubItem : {
      property1 : customObject.Item.SubItem.property1, //also saves with customObject.getItem().SubItem.getProperty1()
      property2 : customObject.Item.SubItem.property2
    }
  }
});

吸气剂/二传手是

MyClass.prototype.getItem = function(){ ... };

我的 Item 对象非常大,我宁愿不必指定每个子属性...

当我使用 console.log(customObject.Item) 查看我的 Item 对象或通过我的 API 作为 JSON 返回它时,它具有我期望的所有嵌套属性(SubItem,...)。

项目定义为:

SubItem = require('SubItemClass.js');

function MyClass(){
  this.Item = {
    SubItem : new SubItem()
  }
}

并且 SubItem 被定义为

function SubItem(){
  this.property1 = '';
  this.property2 = 0;
}

该模型似乎按预期工作,因为如果我对数据进行硬编码或指定要保存到模型的每个属性,则可以将数据保存到模型...

无论如何,这是代码:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var subItemDefinition = {
  Property1 : {type:String},
  Property2 : {type:Number},    
};

var itemDefinition = {
  SubItem : subItemDefinition
};

var customDefinition = {
  Item : itemDefinition
};

var customSchema = new Schema(customDefinition); 
module.exports = mongoose.model('ModelToSave', customSchema);

谢谢你的帮助

我遇到了这种令人沮丧的情况,并对 Mongoose 网站上记录的解决方案感到有些惊讶。

所以这意味着保存嵌套数组/对象属性(在您的情况下为 Item ),您需要明确指定更改.markModified('Item')

var objectToSave = new ModelToSave({
  _id : req.params.id, 
  Item : customObject
});
objectToSave.markModified('Item');
objectToSave.save();

由于它是无模式类型,您可以将值更改为您喜欢的任何其他值,但 Mongoose 无法自动检测和保存这些更改。 要“告诉”Mongoose Mixed 类型的值已更改,请调用文档的 .markModified(path) 方法,将路径传递给您刚刚更改的 Mixed 类型。

-- http://mongoosejs.com/docs/schematypes.html#mixed

暂无
暂无

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

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