根據檔案,我有以下架構:
const toolRecordSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId },
});
toolRecordSchema.virtual("user", {
ref: "User",
localField: "userId",
foreignField: "_id",
justOne: true,
})
當我填充虛擬時,什么也沒有發生:
db.ToolRecord.find().populate("user")
但是,如果我在模式中添加“ref” userId
,并且 do .populate("userId")
,它會按預期作業,這意味著問題不在于模型之間的關系,而在于虛擬群體。
任何想法我做錯了什么?
如果我添加mongoose.set("debug", true)
,我可以看到.populate("user")
在 mongoose 除錯日志中將此輸出添加到查詢產品中:
users.find({}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
.populate("userId")
并在此日志中添加(有效的)產品:
users.find({ _id: { '$in': [ new ObjectId("631a1fe960d1f82c7fa51a06") ], [Symbol(mongoose#trustedSymbol)]: true }}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
所以我們可以看到問題出在哪里。問題是為什么虛擬人口不起作用?
我正在運行貓鼬 6
uj5u.com熱心網友回復:
您需要virtuals: true
在toJSON
和選項上添加選項toObject()
。
const toolRecordSchema = new mongoose.Schema(
{
userId: { type: mongoose.Schema.Types.ObjectId },
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
uj5u.com熱心網友回復:
您在模型檔案中添加此代碼。將此代碼添加到資料庫模型代碼的末尾。
{
toJSON: { virtuals: true },
toObject: { virtuals: true }}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506436.html
下一篇:Mongoose通過陣列洗掉檔案