在mongoose中,是否有辦法使查詢依賴于另一個模式的另一個檔案?
假設我有一個用戶,他有一個專案串列,我想通過ID找到一個專案,但前提是所提供的用戶在其專案串列中擁有該專案ID。
專案模式(從Document延伸):
const projectSchema = new Schema< ProjectSchema, ProjectModel> (
{
name: { type: String, required: true, trim: true },
description: { type: String, default: ''/span>, trim: true },
},
{
collection: 'project',
timestamps: true。
versionKey: false,
toJSON: { virtuals: true },
toObject: { virtuals: true },
},
);
用戶模式(從Document延伸):
const userSchema = new Schema < UserSchema, UserModel>(
{
email: { type: String, unique: true, required: true, trim: true },
projectIds: { type: [Schema. Types.ObjectId], default。[], ref: 'Project' }。
},
{ collection: 'user', timestamps: true, versionKey: false },
);
所以我想獲得有ID的專案,并且在資料庫中,該專案在用戶的projectIds陣列中。
export async function findProjectForUser(user。User, id: string) {
//從資料庫中通過用戶ID獲取用戶(安全原因)。
const dbUser = await UserModel.findById(user.id)。
if(!dbUser) return undefined; // 401
// check if user has id in projectId array.
const hasProject = dbUser.projectIds. find(pId => pId == id);
if(!hasProject) return undefined // 401
// fetch project from db by id
const project = await ProjectModel.findById(id)。
// => 我可以把這兩個查詢合并成一個嗎?。
return專案。
}
uj5u.com熱心網友回復:
db.users.aggregate( [
{ $match: { _id: user.id }},
{ $unwind: "$projectIds"},
{ $lookup: {
from: ProjectModel.collection.name。
as: "project"。
pipeline: [
{ $match: { _id: id }}.
]
}}
])
.map(doc => doc.project) 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331067.html
標籤:
上一篇:如何處理相互沖突的同伴依賴關系?
下一篇:用直角三角形規則進行整合
