繁体   English   中英

MongoDB:填充或查询两个集合

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

我想要实现的是通过_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
            }
        }
    }
}

我也想通过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.

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