我试图通过使用populate来获取嵌套数据(一个大模式有许多属性,其中一个属性就像另一个模式的id数组)。我想通过使用id来查找嵌套模式。
第一个模式-扇区:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const sectorsSchema = new Schema({
title: { type: String, required: true },
description: { type: String, required: true },
img: { type: String, required: true },
poc: { type: String, required: true },
PhoneNum: { type: String, required: true },
EmailPOC: { type: String, required: true },
subSectors: [
{ type: mongoose.Types.ObjectId, required: true, ref: "subSectors" },
], //store all objectId of Place as an array
file_gallery: [
{ type: mongoose.Types.ObjectId, required: true, ref: "Files" },
], //store all objectId of Place as an array
web_id: { type: mongoose.Types.ObjectId, required: true, ref: "MainContent" },
});
module.exports = mongoose.model("sectors", sectorsSchema);
字符串
文档示例:x1c 0d1x的数据
和分部门:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const subSectorsSchema = new Schema({
title: { type: String, required: true },
desc: { type: String, required: true },
img: { type: String, required: true },
poc: { type: String, required: true },
PhoneNum: { type: String, required: true },
EmailPOC: { type: String, required: true },
QnA: [{ type: mongoose.Types.ObjectId, required: true, ref: "QnA" }], //store all objectId of QnA as an array
file_gallery: [
{ type: mongoose.Types.ObjectId, required: true, ref: "Files" },
], //store all objectId of Files as an array
sector_id: { type: mongoose.Types.ObjectId, required: true, ref: "sectors" },
web_id: { type: mongoose.Types.ObjectId, required: true, ref: "MainContent" },
});
module.exports = mongoose.model("subSectors", subSectorsSchema);
型
文档示例:
的
正如你所看到的,这两个文档之间有一个连接(每个扇区可以有许多子扇区)。
我试图通过使用mongoose的populate方法来获取subSector。这是我的代码,但它不工作…
const subSectorId = req.params.subSectorid;
const sectorId = req.params.sectorid;
let sector;
try {
sector = await Sectors.findById(sectorId)
.findOne({ _id: subSectorId })
.populate("subSectors");
} catch (err) {
const error = new HttpError(
"Something went wrong, could not delete sector.",
500
);
return next(error);
}
if (!sector) {
const error = new HttpError("Could not find sector for this id.", 404);
return next(error);
}
型
我得到的回应:“message”:“找不到此ID的扇区。”
我发送的参数是(你可以在图像中看到,它们属于我附上的文档照片):
const subSectorId = 62dd1c9f720d07f2488c65a3
const sectorId = 62dd21a82bf3289ef6f08219
型
谢谢你的好意
2条答案
按热度按时间91zkwejq1#
我自己解决问题:)
字符串
vshtjzan2#
可以使用聚合管道而不是填充
字符串