问题
I'm puzzled as of why Mongoose isn't saving my object:
var objectToSave = new ModelToSave({
_id : req.params.id,
Item : customObject.Item //doesn't save with customObject.getItem() neither
});
But is saving this; as is below or with hardcoded values:
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
}
}
});
The getters/setters are
MyClass.prototype.getItem = function(){ ... };
My Item object is quite big, and I'd rather not have to specify every single sub properties...
When I view my Item object with console.log(customObject.Item) or when I return it through my API as JSON, it has all the nested properties (SubItem, ...) that I'm expecting.
Item is defined as:
SubItem = require('SubItemClass.js');
function MyClass(){
this.Item = {
SubItem : new SubItem()
}
}
And SubItem is defined as
function SubItem(){
this.property1 = '';
this.property2 = 0;
}
The model seems to work as expected, because If I hardcode data or if I specify every single properties to save to the model, I can save the data to the Model...
here's the code anyway:
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);
Thanks for your help
回答1:
I came across this frustrating situation and was a little surprised by the documented solution from Mongoose's website.
so what this means is to save nested array/object properties (Item in your case), you need to be explicit in specifying the change .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.
-- http://mongoosejs.com/docs/schematypes.html#mixed
来源:https://stackoverflow.com/questions/24054552/mongoose-not-saving-nested-object