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) { ... });
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) { ... });
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.
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);
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.