我有表格模型用户
const schema = new mongoose.Schema(
{
telegramId_parent: {
type: Number,
default: null,
},
telegramId: {
type: Number,
required: true,
unique: true,
},
telegramName: {
type: String,
},
}
);
数据库数据
[
{
_id: new ObjectId('63e8b3951e2a'),
telegramId: 111,
telegramName: 'ParentTest',
telegramId_parent: null,
},
{
_id: new ObjectId('63e8fa887473'),
telegramId: 100,
telegramName: 'child1',
telegramId_parent: 200,
},
{
_id: new ObjectId('45a2ec90e'),
telegramId: 101,
telegramName: 'child2"',
telegramId_parent: 200,
},
{
_id: new ObjectId('63c92e'),
telegramId: 102,
telegramName: 'child1-1"',
telegramId_parent: 100,
},
{
_id: new ObjectId('63e96'),
telegramId: 200,
telegramName: 'Name1',
telegramId_parent: 111,
},
];
我想获取子用户.telegramId=200,深度=3
那就是,我期待这个结果:
{
_id: new ObjectId('63e96'),
telegramId: 200,
telegramName: 'Name1',
telegramId_parent: 111,
childs:[
{
_id: new ObjectId('63e8fa887473'),
telegramId: 100,
telegramName: 'child1',
telegramId_parent: 200,
},
{
_id: new ObjectId('45a2ec90e'),
telegramId: 101,
telegramName: 'child2"',
telegramId_parent: 200,
},
{
_id: new ObjectId('63c92e'),
telegramId: 102,
telegramName: 'child1-1"',
telegramId_parent: 100,
},
]
}
我的疑问:
User.aggregate([
{ $match: { telegramId: 200 } },
{
$graphLookup: {
from: 'Users',
startWith: '$telegramId',
connectFromField: 'telegramId',
connectToField: 'telegramId_parent',
as: 'child',
maxDepth: 3,
},
},
]);
结果应该是这样的,
200->>> UserId
/\
/ \
100 101
/
/
102
任何帮助都将不胜感激,以获得层次结构的结果与水平?
我没能得到预期的结果。但由于某种原因,他没有找到它,我得到了这样的结果
{
_id: new ObjectId('63e96'),
telegramId: 200,
telegramName: 'Name1',
telegramId_parent: 111,
childs:[]
}
他为什么找不到呢
1条答案
按热度按时间tp5buhyn1#
$graphLookup“from”字段接受集合名称,而不是mongoose模型。Mongoose在创建集合时会自动将模型名称小写,因此请使用“users”而不是“Users”: