【发布时间】:2014-07-26 02:43:43
【问题描述】:
我很困惑为什么 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
}
}
});
getter/setter 是
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);
感谢您的帮助
【问题讨论】:
-
您是如何定义
ModelToSave的架构的。从这里看起来类型不匹配。您能否编辑您的问题以包含此内容。 -
看起来好像无法访问 customObject.Item,因此我必须将其分解为所有子属性的原因...当我从 POST 保存数据时,我使用相同的代码结构如上,即只定义要保存的模型对象,仅使用其更高级别的属性,如“Item : req.body.Item”
标签: javascript node.js mongodb mongoose javascript-objects