简体   繁体   English

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

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

I have the following scheme in the mongoose 我的猫鼬有以下计划

var Schema = mongoose.Schema;

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

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


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

if create new document like: 如果创建新文档,例如:

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

game.field[0].fooMethod();

it's correctly work. 它正常工作。 But if you run this code: 但是,如果运行此代码:

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

i get TypeError: game.field[0].fooMethod is not a function and console log is 我收到TypeError:game.field [0] .fooMethod不是函数,控制台日志是

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

how correct load sub-document with all schema methods? 如何使用所有架构方法正确加载子文档?

You have to define the methods on the embedded schema before defining the parent schema. 您必须先在嵌入式架构上定义方法,然后再定义父架构。

Also you have to reference CellSchema instead of 'Cell' 另外,您必须引用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