我很困惑为什么 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
}
}
});
getters/setters 是
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();
Since it is a schema-less type, you can change the value to anything else you like, but Mongoose loses the ability to auto detect and save those changes. To "tell" Mongoose that the value of a Mixed type has changed, call the .markModified(path) method of the document passing the path to the Mixed type you just changed.
关于javascript - Mongoose 不保存嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24054552/