一点背景:我正在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);
然后在我的数据层中,我可以发出这样的查询并获得预期结果:
Card.find().sort('cardName').exec(function (err, cardList) { ... });
但是,一旦我添加一个名为Deck的新架构,其中包含对Card架构的引用:
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来说还是新手,所以我确信我错过了一些简单的东西。
答案 0 :(得分:3)
好吧,我弄清楚问题是什么。有点像一个白痴,但在这里。我同时在同一个文件中定义了Card和Deck模式,因为它们是相关的并且它是有意义的。在文件的最后,我有以下内容:
module.exports = mongoose.model('Card', CardSchema);
module.exports = mongoose.model('Deck', DeckSchema);
这意味着我的卡架构从未暴露过,因为我没想到我何时导出模型。我将Deck架构移动到一个单独的文件中,现在一切正常。
愚蠢的错误,但现在我知道了。知道是成功的一半。