繁体   English   中英

NodeJs,Mongoose 查找和填充工作,但聚合,匹配和查找不

[英]NodeJs, Mongoose find and populate works but aggregate, match and lookup doesn't

我的聚合有问题。我需要返回具有相同所有者 ID 的项目列表。 我作为查询参数传递的所有者 ID。我已经尝试了 $match 没有 $in,

我尝试将我的 id 转换为 mongoose.Types.ObjectId (我的事件得到一个错误)。 但是我只完成了空的 object 作为回报..

exports.getContainersByOwner = async (req: Request, res: Response) => {
  const { id }: any = req.query;

  try {
    const containers = await Container.aggregate([
      {
        $lookup: {
          from: "containerstypes",
          localField: "containerTypeID",
          foreignField: "_id",
          as: "containerTypes",
        },
      },
      {
        $lookup: {
          from: "owners",
          localField: "ownerId",
          foreignField: "_id",
          as: "owner",
        },
      },
      { $unwind: "$containerTypes" },
      { $unwind: "$owner" },
      { $match: { "owner._id": { $in: [id] } } },
    ]);
    res.status(200).json(containers);
  } catch (err) {
    res.status(404).json({ success: false, msg: "Container not found" });
  }
};

如果我从我的代码 api 中删除行 $match 会返回所有可以的项目,但我需要实现返回的项目具有相同的 id...我需要匹配彩色 id (owner._id) 在此处输入图像描述

容器的 model 是:

const ContainerSchema = new mongoose.Schema({
  ownerId: { type: Schema.Types.ObjectId, ref: "Owners", required: true },
  manufacturingNo: { type: String, required: true },
  IdentificationNo: { type: String, required: true },
  manufacturingDate: { type: Date, required: true },
  nextInspectionDate: { type: Date, required: true },
  certificateNo: { type: String, required: false },
  containerTypeID: {
    type: Schema.Types.ObjectId,
    ref: "ContainersType",
    required: true,
  },
});

如果我使用这种方法它可以工作,但是 object 结构不正确,所以在前端有更多的变化要做.. 目前这是不可能的

  try {
    const containers = await Container.find({
      ownerId: id,
    })
      .populate("containerTypeID")
      .populate("ownerId");
    res.status(200).json(containers);
  } catch (err) {
    res.status(404).json({ success: false, msg: "Container not found" });
  }

您的$match在逻辑上是错误的:

 { $match: { "owner._id": { $in: [id] } } }

由于id本身是一个 ID 列表,因此您的 $in 成为列表列表 ([[]])。 试试这个:

 { $match: { "owner._id": { $in: id } } }

暂无
暂无

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

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