node.js - 如何使用聚合从 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 什么都不返回(空数组)。
怎么了?
解决方案
[解决]
问题出在方案中:
companyId: {
type: String,
required: true,
},
正确的是:
companyId: {
type: Schema.Types.ObjectId,
required: true,
},
推荐阅读
- asp.net - 每次部署后强制启用 Asp.net Impersonation
- c# - 如何使用 CSVhelper 库遍历 csv 文件中的列?使用:动态对象
- java - Eclipse 2020-06 Java 仅显示 localJavaApplication 启动器,没有 javaApplet 启动器
- python - 如何将 plt.subplots 集成到我的代码中?
- command-line - 安装 NativeScript 后找不到 TNS 命令
- c# - 使用 C# 访问 JSON 数组中的数据
- python - 如何将熊猫组转换为不同的列?
- android - 使用 Outlook 打开 webcal URI
- ios - 如何获得设备移动的距离?
- java - Spring Boot 模块 bean 返回错误编码的字符串