node.js - 加载后如何在 mongoose 子文档中使用 Schema 方法

标签 node.js mongodb mongoose

我在 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/

相关文章:

ios - 在 iOS 中,http 204 响应返回空白页面,有办法阻止这种情况吗?

javascript - Node Express 4 在多次 API 调用后发送响应

javascript - 构造嵌套对象的路径

node.js - Node Js 链接响应

javascript - 无法在 Javascript 中检索对象属性

javascript - redux.js 中的 fetch(url) 使用错误的端口

mongodb - 从数组中获取匹配的嵌入文档

mongodb - 在特定文档上放松

node.js - Underscore.js _.extend 函数在架构中未定义时不会复制 mongoose 模型属性?

node.js - ffmpeg - ffmpeg aws lambda 函数错误