簡體   English   中英

加載后如何在貓鼬子文檔中使用Schema方法

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

我的貓鼬有以下計划

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM