我正在 mongoose 和 GraphQL 上设置后端,但在 mongoose 中使用虚拟填充时遇到了一些问题。
这是一个运行在 5.4.0 版 mongoose 和 11.5.0 版 node 上的 node.js 应用程序。我试图遵循这两个指南但没有成功
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);
newGame 对象甚至不包含 gameStatus 属性。如果我添加 .toJSON({virtuals: true})
gameStatus 显示为 null。
以下是来自 mongo 的 JSON 对象的示例
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
}
我希望上面的代码让我查询我的游戏对象并获得具有虚拟填充的 gameStatus 对象的游戏对象,但它返回 null。如果有人可以看看我的问题,我会很高兴。
最佳答案
命名集合时出错。 Mongoose 通常在集合名称中添加“es”,作为复数形式。在 mongoose mongoose.set("debug", true);
中启用调试并看到它正在寻找错误的集合后,我发现了这一点。在这种情况下,集合名称缺少“es”。
这个堆栈溢出线程稍微解释了一下
Why does mongoose always add an s to the end of my collection name
我通过将 collection: "gameStatus"
添加到我的 mongoose 模式选项中解决了这个问题。
关于javascript - Mongoose 虚拟填充返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54327212/