Node.js “如何在对象之间连接两个集合”_id";在MongoDB
关于,我正在尝试合并两个集合Node.js “如何在对象之间连接两个集合”_id";在MongoDB,node.js,mongodb,express,Node.js,Mongodb,Express,关于,我正在尝试合并两个集合 产品 类别 关键是它的唯一关系是对应文档的ObjectId,请参见: 产品系列 { "_id": Object(607a858c2db9a42d1870270f), "code":"CODLV001", "name":"Product Name", "category":"607a63e5778bf
- 产品
- 类别
{
"_id": Object(607a858c2db9a42d1870270f),
"code":"CODLV001",
"name":"Product Name",
"category":"607a63e5778bf40cac75d863",
"tax":"0",
"saleValue":"0",
"status":true
}
{
"_id": Object(607a63bf06e84e5240d377de),
"name": "Diversey Care",
"status": true
},
{
"_id": Object(607a63e5778bf40cac75d863),
"name": "Sani Tisu Profesional",
"status": true
}
类别集合
{
"_id": Object(607a858c2db9a42d1870270f),
"code":"CODLV001",
"name":"Product Name",
"category":"607a63e5778bf40cac75d863",
"tax":"0",
"saleValue":"0",
"status":true
}
{
"_id": Object(607a63bf06e84e5240d377de),
"name": "Diversey Care",
"status": true
},
{
"_id": Object(607a63e5778bf40cac75d863),
"name": "Sani Tisu Profesional",
"status": true
}
我在做什么
.collection(collection)
.aggregate([
{
$lookup: {
from: 'categories',
localField: 'products.category',
foreignField: 'categories._id',
as: 'category',
},
},
])
.toArray();
我得到了什么?
{
_id: 607a858c2db9a42d1870270f,
code: 'CODLV001',
name: 'Product Name',
category: [ [Object], [Object] ],
tax: '0',
saleValue: '0'
}
{
_id: 607a858c2db9a42d1870270f,
code: 'CODLV001',
name: 'Product Name',
category: [ [Object] ], // or every field from category collection without an array object
tax: '0',
saleValue: '0'
}
我期待什么?
{
_id: 607a858c2db9a42d1870270f,
code: 'CODLV001',
name: 'Product Name',
category: [ [Object], [Object] ],
tax: '0',
saleValue: '0'
}
{
_id: 607a858c2db9a42d1870270f,
code: 'CODLV001',
name: 'Product Name',
category: [ [Object] ], // or every field from category collection without an array object
tax: '0',
saleValue: '0'
}
但是,如果我使用这种方式,类别字段是一个空数组
{
$lookup: {
from: 'categories',
localField: 'category',
foreignField: '_id',
as: 'category',
},
},
那么,我做错了什么(以防万一我是MongoDB世界的新手)?您的查询中几乎没有修复
collection字段products
是字符串类型,category
字段categories
是objectId类型,因此我们需要使用\u id
$toObjectId
,将$lookup
作为localField
传递,将category
作为foreignField
传递,无需指定集合名称\u id