简体   繁体   中英

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:

{
    "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.

Can I do this with Mongoose populate ? My approach would be to first do a User.findOne() and then check the project.id and to a 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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