首页 > 解决方案 > 如何使用聚合从 mongodb 中的两个集合中查询?

问题描述

我的 mongoDB 中有以下两个集合:

产品:

[
    {
        "_id": "5ebb0984e95e3e9e35aab3bf",
        "name": "Product 1",
        "brand": "ABC",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    },
    {
        "_id": "5ebdb9f3d943ae000a4a9714",
        "name": "Product 2",
        "brand": "DEF",
        "code": "7891910000190",
        "description": "Lorem Ipsum"
    }
]

库存商品:

[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed058da75e4e01013f5779d",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04cede9e43cee79734b93",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "companyId": "5ed0491bf9a892a5fd9b4d9b",
        "branchId": "5ed049a8f9a892a5fd9b4d9e",
        "inventoryId": "5ed04d01e9e43cee79734b95",
        "productId": "5ebb0984e95e3e9e35aab3bf"
    }
]

我想得到以下结果:

[
    {
        "_id": "5ed0586b7f2cfe02387d0706",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    },
    {
        "_id": "5ed059483da3bafccb34cec3",
        "data": {
            "_id": "5ebb0984e95e3e9e35aab3bf",
            "brand": "ABC",
            "code": "7891910000190",
            "description": "Lorem Ipsum",
            "name": "Product 1",
        }
    }
]

我的 NodeJS 和 MongoDB 聚合如下所示:

const mongoose = require("mongoose");
const StockGoods = mongoose.model("StockGoods");
ObjectId = require("mongodb").ObjectID;

exports.getProducts = async (companyId, branchId, inventoryId) => {
  const response = await StockGoods.aggregate([
    {
      $match: {
        companyId: new ObjectId("5ed0491bf9a892a5fd9b4d9b"), // new ObjectId(companyId)
        inventoryId: new ObjectId("5ed04d01e9e43cee79734b95"), // new ObjectId(inventoryId)
        branchId: new ObjectId("5ed049a8f9a892a5fd9b4d9e"), // new ObjectId(branchId)
      },
    },
    {
      $lookup: {
        from: "products",
        localField: "productId",
        foreignField: "_id",
        as: "inventory_docs",
      },
    },
    {
      $project: {
        data: "$inventory_docs",
      },
    },
    { $unwind: "$data" },
  ]);
  return response;
};

这是同一个数据库和上面描述的聚合函数,你可以检查这个:https ://mongoplayground.net/p/FRgAIfO2bwh 。

但是,当我使用 nodejs 时,这个函数聚合不起作用。我的 API 什么都不返回(空数组)。

怎么了?

标签: node.jsmongodbmongooseaggregation-framework

解决方案


[解决]

问题出在方案中:

companyId: {
    type: String,
    required: true,
},

正确的是:

companyId: {
    type: Schema.Types.ObjectId,
    required: true,
},

推荐阅读