我在 Mongoose 中有以下方案
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]
});
关于node.js - 加载后如何在 mongoose 子文档中使用 Schema 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34376346/