mongoose不保存嵌套的对象

我感到困惑的是为什么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)或当我通过我的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网站提供的解决scheme感到有点惊讶。

所以这意味着要保存嵌套的数组/对象属性(在你的情况下,项目),你需要明确指定的变化.markModified('Item')

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

由于它是一个无模式types,您可以将其值更改为其他任何您喜欢的值,但Mongoose失去了自动检测和保存这些更改的function。 为了“告诉”Mongoose混合types的值已经改变,调用文档的.markModified(path)方法,将path传递给你刚才改变的混合types。

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