【问题标题】:Trouble when trying to save an Object on a document with nodejs throught mongoose尝试使用nodejs通过猫鼬将对象保存在文档上时出现问题
【发布时间】:2014-05-12 08:14:59
【问题描述】:

我得到了这个架构:

var schema = {
    id                  : { type:Number, unique:true },
    name                : String,
    kind                : String,
    size                : Object,
    skin                : String,
    position            : Object,
    velocity            : Object,
    acceleration        : Object,
    spritesheet         : String,
    animation           : Object,
    animations          : Object,
    currentAnimation    : String,
    visible             : Boolean
};

注意:以下this 是业务对象的一个​​实例。 this.dao 是这样设置的:

var elementSchema = mongoose.Schema(schema);
this.dao = mongoose.model('Element', elementSchema);

这里有我用来获取数据的方式:

this.dao.findOne({"id":id},(function(err,result){
    this.data = result;
}).bind(this)) ;

我这样保存在我的对象中:

this.data.save((function(err,result,row){
    if(err !== null) throw err;
    if(row === 1) {
        console.log(result);
        this.emit("saved");
    }
}).bind(this)) ;

问题:

它适用于架构中的很多类型,但我遇到了 Object 类型的奇怪问题。

当我尝试保存我的数据时,它适用于所有类型,但不适用于对象类型。控制台中显示 {x:100,y:200} 的 console.log(this.data.position)。但是,如果我像这样更改data.positiondata.position = {x:100,y:200} 并在它工作后保存!

我的假设:

可能是我的 data.position 有一个原型属性,当我尝试保存它并且数据无法保存时。问题是我没有错误,并且在保存函数的回调中,result var 显示了我的应用程序数据...

注意:我只是看到它不是官方的 SchemaType (http://mongoosejs.com/docs/schematypes.html)...

我的问题:

如何使用 mongoose 在文档中正确保存 Object ? 为什么保存失败时我没有错误?

(我更新到最新版本 3.8.8 并遇到同样的问题)。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我明白了: http://mongoosejs.com/docs/api.html#document_Document-markModified

    在混合类型(我的对象类型是什么)中,我们需要向 mongoose 指定它们使用下面的函数进行了更改:

    this.data.markModified('position');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      • 2021-07-06
      • 2020-06-24
      • 2021-06-26
      • 2014-08-03
      • 1970-01-01
      • 2020-07-27
      相关资源
      最近更新 更多