use*_*446 6 javascript mongoose mongodb node.js javascript-objects
我很困惑,为什么Mongoose没有保存我的对象:
var objectToSave = new ModelToSave({
_id : req.params.id,
Item : customObject.Item //doesn't save with customObject.getItem() neither
});
Run Code Online (Sandbox Code Playgroud)
但是节省了这个; 如下所示或硬编码值:
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
}
}
});
Run Code Online (Sandbox Code Playgroud)
吸气剂/孵化器是
MyClass.prototype.getItem = function(){ ... };
Run Code Online (Sandbox Code Playgroud)
我的Item对象非常大,我宁愿不必指定每个子属性......
当我使用console.log(customObject.Item)查看我的Item对象或当我通过我的API作为JSON返回它时,它具有我期望的所有嵌套属性(SubItem,...).
项目定义为:
SubItem = require('SubItemClass.js');
function MyClass(){
this.Item = {
SubItem : new SubItem()
}
}
Run Code Online (Sandbox Code Playgroud)
SubItem定义为
function SubItem(){
this.property1 = '';
this.property2 = 0;
}
Run Code Online (Sandbox Code Playgroud)
该模型似乎按预期工作,因为如果我硬编码数据或如果我指定保存到模型的每个属性,我可以将数据保存到模型...
无论如何这里是代码:
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);
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助
Jam*_*oad 14
我遇到了这种令人沮丧的情况,并对Mongoose网站上记录的解决方案感到有些惊讶.
所以这意味着保存嵌套数组/对象属性(在您的情况下为Item),您需要明确指定更改 .markModified('Item')
var objectToSave = new ModelToSave({
_id : req.params.id,
Item : customObject
});
objectToSave.markModified('Item');
objectToSave.save();
Run Code Online (Sandbox Code Playgroud)
由于它是无模式类型,因此您可以将值更改为您喜欢的任何其他值,但Mongoose无法自动检测并保存这些更改.要"告诉"Mongoose混合类型的值已更改,请调用文档的.markModified(path)方法,将路径传递给刚刚更改的Mixed类型.
- http://mongoosejs.com/docs/schematypes.html#mixed
| 归档时间: |
|
| 查看次数: |
3540 次 |
| 最近记录: |