Node.js Mongoose:在另一个文档中用作引用时集合未填充

Node.js Mongoose:在另一个文档中用作引用时集合未填充,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,有一点背景:我正在node.js中构建一个在线多玩家web应用程序,有点类似于Magic:The Gathering(但不是m:TG克隆)。所以我有了扑克牌和扑克牌的概念。如果我只有一个卡片模式,我可以很好地查询它。这是我的卡片模式: var CardSchema = new Schema({ cardName: { type: String, required: true, unique: true }, cardType: { type: String, required:

有一点背景:我正在node.js中构建一个在线多玩家web应用程序,有点类似于Magic:The Gathering(但不是m:TG克隆)。所以我有了扑克牌和扑克牌的概念。如果我只有一个卡片模式,我可以很好地查询它。这是我的卡片模式:

var CardSchema = new Schema({
    cardName: { type: String, required: true, unique: true },
    cardType: { type: String, required: true }
    health: { type: Number },
    power: { type: Number }
});

module.exports = mongoose.model('Card', CardSchema);
var DeckSchema = new Schema({
    deckName: { type: String, required: true, unique: true },
    cards: [{ type: Schema.Types.ObjectId, ref: 'Card' }]
});

module.exports = mongoose.model('Deck', DeckSchema);
然后在我的数据层中,我可以发出这样的查询并返回预期结果:

Card.find().sort('cardName').exec(function (err, cardList) { ... });
但是,一旦我添加了一个名为Deck的新模式,该模式包含对卡模式的引用:

var CardSchema = new Schema({
    cardName: { type: String, required: true, unique: true },
    cardType: { type: String, required: true }
    health: { type: Number },
    power: { type: Number }
});

module.exports = mongoose.model('Card', CardSchema);
var DeckSchema = new Schema({
    deckName: { type: String, required: true, unique: true },
    cards: [{ type: Schema.Types.ObjectId, ref: 'Card' }]
});

module.exports = mongoose.model('Deck', DeckSchema);
我上一次获取所有卡的查询没有返回任何内容:

Card.find().sort('cardName').exec(function (err, cardList) { ... });

我不确定我是否在人口方面遗漏了什么。我查看了Mongoose关于人口的文档,似乎不明白为什么添加这个新模式会导致我无法检索卡片。我确信这是一个简单的问题,但我对Mongoose和MongoDB还是相当陌生的,所以我确信我错过了一些简单的问题。

好吧,我发现了问题所在。有点像个白痴,但就是这样。我在同一个文件中定义了Card和Deck模式,因为它们是相关的,这是有意义的。在文件末尾,我有以下内容:

module.exports = mongoose.model('Card', CardSchema);
module.exports = mongoose.model('Deck', DeckSchema);
这意味着我的卡片模式从未公开,因为我在导出模型时没有思考。我将Deck模式移动到一个单独的文件中,现在一切都正常了


愚蠢的错误,但现在我知道了。知道是成功的一半。

好吧,我知道问题出在哪里了。有点像个白痴,但就是这样。我在同一个文件中定义了Card和Deck模式,因为它们是相关的,这是有意义的。在文件末尾,我有以下内容:

module.exports = mongoose.model('Card', CardSchema);
module.exports = mongoose.model('Deck', DeckSchema);
这意味着我的卡片模式从未公开,因为我在导出模型时没有思考。我将Deck模式移动到一个单独的文件中,现在一切都正常了


愚蠢的错误,但现在我知道了。而了解是成功的一半。

我觉得你的模式还不错。我怀疑问题与此完全无关。您甚至没有调用
.populate('cards')
或查询
cards
集合。你确定你在这里做对了吗?嗯,我有一个管理卡的管理界面(基本上是CRUD操作)。如果我没有卡片组模式,那么我可以在没有问题的情况下成功查询卡片集合。一旦我添加了Deck模式,以前工作的那些查询就不再返回数据了。这很奇怪。这是我的github回购的链接,我可能没有包含足够的信息。模型在/Models中,数据层代码在/datamodels中。在我看来,您的模式还不错。我怀疑问题与此完全无关。您甚至没有调用
.populate('cards')
或查询
cards
集合。你确定你在这里做对了吗?嗯,我有一个管理卡的管理界面(基本上是CRUD操作)。如果我没有卡片组模式,那么我可以在没有问题的情况下成功查询卡片集合。一旦我添加了Deck模式,以前工作的那些查询就不再返回数据了。这很奇怪。这是我的github回购的链接,我可能没有包含足够的信息。模型在/Models中,数据层代码在/datathankyou中,我犯了同样的错误谢谢,我犯了同样的错误