我困惑的是,为什么猫鼬是不是救了我的对象:猫鼬不节能嵌套对象
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
}
}
});
的getter/setter方法是
MyClass.prototype.getItem = function(){ ... };
我的项目目标是比较大的,我宁愿没有指定每一单个子属性...
当我用console.log(customObject.Item)查看我的Item对象时,或者当我通过API将它作为JSON返回时,它具有我期待的所有嵌套属性(SubItem,...)。
项目被定义为:
SubItem = require('SubItemClass.js');
function MyClass(){
this.Item = {
SubItem : new 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);
感谢您的帮助
你是如何定义的'ModelToSave'的模式。它看起来像来自这里的类型不匹配。你可以编辑你的问题,包括这个请。 –
它看起来像是无法访问customObject.Item,因此我必须将其分解为所有子属性的原因... 当我从POST中保存数据时,我使用与上面相同的代码结构,即只定义要保存的模型对象以及其更高级别的属性,如“Item:req.body.Item” – user1144446