Вы не можете сделать 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
}
}