【问题标题】:How to populate mongoose result with subdocument's array?如何用子文档数组填充猫鼬结果?
【发布时间】:2020-01-21 22:24:59
【问题描述】:

我正在尝试使用子文档填充 mongoose 结果,但我不能。

我试过这段代码,但它得到了这个错误:

MissingSchemaError:尚未为模型“department.subDepartment”注册架构

Mongoose 架构:

const subDepartmentSchema = new Schema({
  name: { type: String, required: true },
  city: { type: String, required: true }
})

const DepartmentSchema = new Schema({
  name: { type: String, required: true },
  city: { type: String, required: true },
  subDepartment: [subDepartmentSchema]
}
)

const UserSchema = new Schema({
  name: { type: String, required: true },
  city: { type: String, required: true },
  department: { type: Schema.Types.ObjectId, required: true, ref: 'department' },
  subDepartment: { type: Schema.Types.ObjectId, required: true, ref: 'department.subDepartment' },
  active: { type: Boolean, required: true, default: true }
}
)

const Department = mongoose.model('department', DepartmentSchema)
const User = mongoose.model('user', UserSchema)

功能:

const result = await User.findById('5d31dfeec4d0af0cb2f448fc').populate('subDepartment')
console.log(JSON.stringify(result.subDepartment))

在数据库中,我必须只有两个文档(部门和用户),子部门应该是部门的子文档

如何填充“子部门”?

【问题讨论】:

    标签: node.js mongoose mongoose-populate


    【解决方案1】:

    您还没有创建subDepartment 模型,只是模式,因此您还在DepartmentSchema 中引用了错误的类型。

    const subDepartment = mongoose.model('subDepartment', subDepartmentSchema) // this line is missing
    const DepartmentSchema = new Schema({
      name: { type: String, required: true },
      city: { type: String, required: true },
      subDepartment: [{ type: Schema.Types.ObjectId, ref:'subDepartment'}]
    }
    

    【讨论】:

    • 我试过但现在结果为空,在数据库上我必须只有两个文档(部门和用户),并且通过解决方案我将添加一个新文档。
    【解决方案2】:

    populate 不能使用像 departments.subDepartments 这样的嵌套字段。相反,您应该填充部门,然后为用户挑选部门的子部门。

    index.js

    const app = require("express")();
    const morgan = require("morgan");
    const bodyParser = require("body-parser");
    const mongoose = require("mongoose");
    const models = require("./models");
    
    app.use(morgan("dev"));
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.post("/init", async (req, res) => {
      const department = await models.Department.create({
        name: "ICT",
        city: "CA",
        subDepartments: {
          name: "Yolo",
          city: "Solo",
        },
      });
      const user = await models.User.create({
        name: "John Wick",
        city: "NY",
        department: department._id,
      });
      return res.status(201).send({
        message: "Created",
        data: {
          user,
          department,
        },
      });
    });
    app.get("/users", async (req, res) => {
      const user = await models.User.findOne().populate("department");
      return res.send({ user });
    });
    
    mongoose.connect("mongodb://root:toor@0.0.0.0:27017/stackoverflow");
    mongoose.connection.on("error", err => console.error(err));
    app.listen(3000, () => console.log("Listening on :3000"));
    
    

    models.js

    const mongoose = require("mongoose");
    
    const Schema = mongoose.Schema;
    
    const DepartmentSchema = new Schema({
      name: { type: String, required: true },
      city: { type: String, required: true },
      subDepartments: [
        {
          name: { type: String, required: true },
          city: { type: String, required: true },
        },
      ],
    });
    
    const UserSchema = new Schema({
      name: { type: String, required: true },
      city: { type: String, required: true },
      department: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: "department",
      },
      active: { type: Boolean, required: true, default: true },
    });
    
    exports.Department = mongoose.model("department", DepartmentSchema);
    exports.User = mongoose.model("user", UserSchema);
    

    GET/users 的请求将返回

    {
        "user": {
            "active": true,
            "_id": "5d8aa2c36ac2502b3c33794b",
            "name": "John Wick",
            "city": "NY",
            "department": {
                "_id": "5d8aa2c36ac2502b3c337949",
                "name": "ICT",
                "city": "CA",
                "subDepartments": [
                    {
                        "_id": "5d8aa2c36ac2502b3c33794a",
                        "name": "Yolo",
                        "city": "Solo"
                    }
                ],
                "__v": 0
            },
            "__v": 0
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-05-16
      • 2017-05-07
      • 2021-02-11
      • 2021-10-07
      • 2016-08-17
      • 2018-11-10
      • 2015-07-28
      • 1970-01-01
      • 2020-04-29
      相关资源
      最近更新 更多