繁体   English   中英

mongoose 填充 object id 的数组

[英]mongoose populate array of object id

我正在尝试通过使用填充来获取嵌套数据(一个大模式有很多属性,其中一个属性就像一个 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);

文档示例: 在此处输入图像描述

和子部门:

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 的填充方法来获取子扇区。这是我的代码,但它不起作用......

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

我得到的响应是:“消息”:“找不到此 ID 的扇区。”

我发送的参数是(你可以在图像中看到它们属于我附加的文档照片):

const subSectorId = 62dd1c9f720d07f2488c65a3
const sectorId = 62dd21a82bf3289ef6f08219

谢谢

我自己解决问题:)

 sector = await Sectors.findById(sectorId).populate({
   path: "subSectors",
   match: { _id: subSectorId },
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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