代码之家  ›  专栏  ›  技术社区  ›  mrks

mongodb:填充或查询两个集合

  •  0
  • mrks  · 技术社区  · 5 年前

    我有以下模式:

    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() .

    1 回复  |  直到 5 年前
        1
  •  1
  •   Colin Daniel    5 年前

    如果在用户模式中引用一个项目数组,那么当查询用户时,将查询与该用户相关联的所有项目。

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

    然后每次查询用户时,都会出现与该用户关联的项目。