如何在加载后在mongoose子文档中使用Schema方法
在mongoose中我有以下scheme
var Schema = mongoose.Schema; var CellSchema = new Schema({ foo: Number, }); CellSchema.methods.fooMethod= function(){ return 'hello'; }; var GameSchema = new Schema({ field: [CellSchema] });
如果创build新的文件如:
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 } ] }
如何正确加载所有模式方法的子文档?
在定义父架构之前,您必须在embedded架构上定义方法。
你也必须引用CellSchema
而不是'Cell'
var CellSchema = new Schema({ foo: Number, }); CellSchema.methods.fooMethod = function() { return 'hello'; }; var GameSchema = new Schema({ field: [CellSchema] });