繁体   English   中英

加载后如何在猫鼬子文档中使用Schema方法

[英]how use Schema methods in mongoose sub-documents after loading

我的猫鼬有以下计划

var Schema = mongoose.Schema;

var CellSchema = new Schema({
    foo: Number,
});

CellSchema.methods.fooMethod= function(){
    return 'hello';
};


var GameSchema = new Schema({
    field: [CellSchema]
});

如果创建新文档,例如:

var cell = new CellModel({foo: 2})
var game = new GameModel();
game.field.push(cell);

game.field[0].fooMethod();

它正常工作。 但是,如果运行此代码:

GameModel.findOne({}, function(err, game) {
    console.log(game);
    game.field[0].fooMethod()
})

我收到TypeError:game.field [0] .fooMethod不是函数,控制台日志是

{ 
  field: 
   [ { foo: 2,
       _id: 5675d5474a78f1b40d96226d }
   ]
}

如何使用所有架构方法正确加载子文档?

您必须先在嵌入式架构上定义方法,然后再定义父架构。

另外,您必须引用CellSchema而不是'Cell'

var CellSchema = new Schema({
    foo: Number,
});
CellSchema.methods.fooMethod = function() {
    return 'hello';
};

var GameSchema = new Schema({
    field: [CellSchema]
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM