猫鼬:在另一个文档中用作引用时,集合未填充 [英] Mongoose: Collection not populating when used as a ref in another document

查看:79
本文介绍了猫鼬:在另一个文档中用作引用时,集合未填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些背景知识:我正在node.js中构建一个在线多人在线Web应用程序,有点类似于Magic:The Gathering(但不是M:TG克隆).所以我有纸牌和套牌的概念.如果我只有卡架构,则可以对其进行查询.这是我的卡模式:

A little background: I'm building an online multi-player web application in node.js somewhat akin to Magic: The Gathering (but not a M:TG clone). So I have the concept of cards and decks. If I have just a card Schema, I can query against it just fine. Here is my card schema:

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

然后在我的数据层中,我可以发出这样的查询并获得预期的结果:

And then in my data layer, I can issue queries like this and get back expected results:

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

但是,一旦我添加了一个称为Deck的新架构,其中包含对Card架构的引用:

However, once I add a new schema called Deck that contains a ref to the Card schema:

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

module.exports = mongoose.model('Deck', DeckSchema);

我之前的获取所有卡的查询未返回任何内容:

My previous query to get all cards returns nothing:

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

我不确定是否缺少人口.我查看了有关人口的Mongoose文档,但似乎无法弄清楚为什么添加此新架构会导致我无法检索卡片.我敢肯定这很简单,但是我对Mongoose和MongoDB还是很陌生,所以我确定我缺少简单的东西.

I'm not sure if I'm missing something with population. I've looked over the Mongoose docs on population and I can't seem to figure out why adding this new schema results in me not being able to retrieve cards. I'm sure it's something simple, but I'm fairly new to Mongoose and MongoDB, so I'm sure I'm missing something simple.

推荐答案

好吧,我发现了问题所在. Kinda感觉自己像个白痴,但事实确实如此.我将Card和Deck模式都定义在同一个文件中,因为它们是相关的,并且很有意义.在文件末尾,我有以下内容:

Well, I figured out what the problem was. Kinda feeling like an idiot, but here it is. I had both the Card and the Deck schema defined in the same file since they were related and it made sense. At the end of the file, I had the following:

module.exports = mongoose.model('Card', CardSchema);
module.exports = mongoose.model('Deck', DeckSchema);

这意味着我的Card模式从未公开,因为我在导出模型时没有考虑.我将Deck模式移到了一个单独的文件,现在一切正常.

Which meant that my Card schema was never being exposed because I wasn't thinking when I exported the models. I moved the Deck schema to a separate file, and now it all works.

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

Stupid mistake, but now I know. And knowing is half the battle.

这篇关于猫鼬:在另一个文档中用作引用时,集合未填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆