javascript - Mongoose 不保存嵌套对象

标签 javascript node.js mongodb mongoose javascript-objects

我很困惑为什么 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.

-- http://mongoosejs.com/docs/schematypes.html#mixed

关于javascript - Mongoose 不保存嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24054552/

相关文章:

javascript - 解决Twilio “Uncaught (in promise) t: Error while setting LastConsumedMessageIndex”错误消息

javascript - asp.net mvc,以 JSON 形式返回多个 View

javascript - 如何为 Express.js 应用程序建立有效的单元测试和场景测试框架?

node.js - 异步eachLimit和同时RangeError : Maximum call stack size exceeded

node.js - Mongoose/NextJS - 模型未定义/编译后无法覆盖模型

javascript - onclick页面去主页没有任何绝对路径

javascript - 通过自定义 Cordova 方案获得安全来源

node.js - 只需从本地主机 :80 to localhost:8080 not working 进行 nginx 反向代理

node.js - Mongoose:3 路文档连接

ruby - 如何验证嵌入字段是否在 before_save 上发生了变化?