I'm setting up a backend on mongoose and GraphQL and I'm having some issues with virtual populate in mongoose.
This is a node.js application running on version 5.4.0 of mongoose and version 11.5.0 of node. I've attempted to follow these two guides without success
http://thecodebarbarian.com/mongoose-virtual-populate https://thecodebarbarian.com/mongoose-4.13-virtual-populate-dynamic-refs-fields
const gameStatusSchema = new mongoose.Schema({
userID: String,
gameID: { type: mongoose.Schema.Types.ObjectId, ref: "Game"},
gameStatus: Number
}, {
timestamps: true,
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
const gameSchema = new mongoose.Schema({
gameTitle: String,
gameDescription: String,
gameType: Number,
gameTypeID: String,
gamePosition: Number,
}, {
timestamps: true,
toObject: { virtuals: true },
toJSON: { virtuals: true }
});
gameSchema.virtual("gameStatus", {
ref: "GameStatus",
localField: "_id",
foreignField: "gameID",
justOne: true
});
const newGame = await Game.findById(id)
.populate("gameStatus");
console.log(newGame);
The newGame object doesn't even contain the gameStatus property. If i add .toJSON({virtuals: true})
gameStatus shows as null.
Below are examples of the JSON objects from mongo
gameStatus object
{
"_id" : ObjectId("5c473a872721eb7327377fa2"),
"userID" : "5c3629deed4593ab3b435614",
"gameID" : ObjectId("5c472bc4b6b5f745bbbd7f6a"),
"gameStatus" : 8
}
game Object
{
"_id" : ObjectId("5c472bc4b6b5f745bbbd7f6a"),
"gameTitle" : "Lotto",
"gameDescription" : "Test",
"gameType" : 1,
"gameTypeID" : "5c472bc4b6b5f745bbbd7f69",
"gamePosition" : 8,
"course" : ObjectId("5c35e5e53757a7a29c33565f"),
"createdAt" : ISODate("2019-01-22T14:42:12.267Z"),
"updatedAt" : ISODate("2019-01-22T14:42:12.267Z"),
"__v" : 0
}
I would expect the code above to let me query my game object and get the game object with the virtually populated gameStatus object, but it returns null. Would love it if someone can take a look at my problem.