[英]MongoDB: Populate or Query for two collections
我有以下模式:
let ProjectSchema = new mongoose.Schema({
title: {
type: String
},
employees: {
user: String, // ==> ObjectId of User from UserSchema
role: String,
workload: Number,
},
description: {
type: String
}
});
let UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true
},
name: {
type: String
},
projects: {
type: Array // ==> ObjectId of Project from ProjectSchema
}
});
我想要實現的是通過_id
或email
獲取用戶,並從他的項目中獲取所有數據,例如:
{
"user": {
"_id": "asdf1234",
"email": "your@email.com",
"name": "Max"
"projects": {
"title": "Project 1",
"description": "Just a text",
"employees": {
"user": "asdf1234",
"role": "developer",
"workload": 40
}
}
}
}
我也想通過ID獲得一個特定的項目,並且employee.user字段應填充正確的用戶數據。
我可以用貓鼬populate
嗎? 我的方法是先執行User.findOne()
,然后檢查project.id,然后檢查Project.findOne()
。
您如何在UserSchema中引用一個項目數組,那樣當您查詢用戶時,您正在查詢與該用戶綁定的所有項目。
let mongoose = require("mongoose");
let Projects = require("./projects");
let UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
trim: true
},
name: {
type: String
},
projects: {
type: [Projects.schema]
}
});
然后,每次您查詢用戶時,它都會附帶與該用戶關聯的項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.