简体   繁体   English

MongoDB:填充或查询两个集合

[英]MongoDB: Populate or Query for two collections

I have the following Schemas: 我有以下模式:

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
  }
});

What I want to achieve is to get the user by _id or email and to get also all data from his projects like: 我想要实现的是通过_idemail获取用户,并从他的项目中获取所有数据,例如:

{
    "user": {
        "_id": "asdf1234",
        "email": "your@email.com",
        "name": "Max"
        "projects": {
            "title": "Project 1",
            "description": "Just a text",
            "employees": {
                "user": "asdf1234",
                "role": "developer",
                "workload": 40
            }
        }
    }
}

And I also want to get a specific project by Id and the employee.user field should be populated with the correct user data. 我也想通过ID获得一个特定的项目,并且employee.user字段应填充正确的用户数据。

Can I do this with Mongoose populate ? 我可以用猫鼬populate吗? My approach would be to first do a User.findOne() and then check the project.id and to a Project.findOne() . 我的方法是先执行User.findOne() ,然后检查project.id,然后检查Project.findOne()

how about in your UserSchema you reference an array of projects, that way when you query for the user you are querying for all the projects tied to the user. 您如何在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]
  }
});

Then every time you query for the user it comes with the projects associated to the user. 然后,每次您查询用户时,它都会附带与该用户关联的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM