當我在我的模型上使用 findById 時,它會回傳除參考另一個檔案的欄位之外的所有欄位。
這是資料庫上的檔案(MongoDB Document):
{
_id: ObjectId("62791a34bfdd286f0d9105b7"),
title: 'yes!',
path: 'public/uploads/birds-1.mp4',
author: {
_id: ObjectId("6276b73f1793107c9027a8ee"),
name: -,
email: -,
image: -,
emailVerified: null,
},
}
這就是我在使用 findById 時得到的(不回傳作者欄位):
{
_id: new ObjectId("62791a34bfdd286f0d9105b7"),
title: 'yes!',
path: 'public/uploads/birds-1.mp4'
}
視頻架構:
mongoose.Schema({
title: {
type: String,
required: true,
},
path: {
type: String,
required: true,
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
})
uj5u.com熱心網友回復:
運行查詢時,您應該明確populate 參考的欄位:
const video = await Videos.findById(_id).populate('author').exec()
您可以在官方檔案上閱讀更多關于查詢人口的資訊。
uj5u.com熱心網友回復:
根據 MongoDB 檔案,您需要對參考的表執行查找。
參考 ID 頁指出您所做的是正確的。您正在將物件的 設定_id為架構中另一個物件的參考點。
然而,它在頂部有一個重要的區別,即您需要使用該$lookup功能來獲取記錄,并且它是一次拉動參考的記錄。
這得到了Stack Overflow 上一個類似的、先前已回答的問題的證實。
Mongoose通過他們稱為“填充”的函式$lookup支持該功能,我假設您希望在其中執行查找,因為您的問題被標記為您正在使用 Mongoose。
如果您需要幫助實作填充功能,請粘貼到您用于從資料庫中檢索資料的代碼中,并且有人可能會幫助您。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/475995.html
