node.js - 尝试通过 mongoose 使用 Node js 将对象保存在文档上时出现问题

标签 node.js mongodb mongoose

我得到了这个架构:

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 类型方面遇到了奇怪的问题。

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

我的假设:

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

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

我的问题:

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

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

最佳答案

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

在混合类型(我的对象类型是什么)中,我们需要向 mongoose 指定它们通过以下函数更改:

this.data.markModified('position');

关于node.js - 尝试通过 mongoose 使用 Node js 将对象保存在文档上时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22787861/

相关文章:

mongodb - Mongoose 拉嵌套数组

node.js - 具有单个数据库的多个 Node 实例

node.js - 游标.sort()和聚合$sort之间的区别

javascript - 为什么只写一个字段而不用它做任何事情?

node.js - 我无法读取 Firebase Functions 上的数据

javascript - 在带有 ejs 的 Node.js 中使用 AJAX

node.js - 在 Linux 机器上安装 npm 时出错

javascript - 如何欺骗 Node.js 将 .js 文件加载为 ES6 模块?

javascript - 链接 Mongoose promise 的语法

node.js - 如何编写给定 mongodb 查询的 mongoose 函数?