Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 加载后如何在mongoose子文档中使用模式方法_Node.js_Mongodb_Mongoose - Fatal编程技术网

Node.js 加载后如何在mongoose子文档中使用模式方法

Node.js 加载后如何在mongoose子文档中使用模式方法,node.js,mongodb,mongoose,Node.js,Mongodb,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 = n

我在猫鼬中有以下计划

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]
});

对不起,就我而言,是的。我更改示例
字段:[CellSchema]
确保它不是字符串,而是对SchemaWaw的直接引用。我修好了。谢谢你的主意。在我的第一个变体代码游戏中,Cell是它的不同模块,其中exports是module.exports=mongoose.model('Cell',CellSchema);这就是我在代码中使用“Cell”的原因我将Cell模块更改为module.exports=mongoose.model('Cell',CellSchema);module.exports.CellSchema=CellSchema;并在游戏模式及其工作中使用字段:[Cell.CellSchema]。伟大的塔克斯!