mongodb聚合查询中如何获取虚拟字段?

how to get virtual fields in aggregation query in mongodb?

我的模型只有一个虚拟字段 show:

modelSchema.virtual('show').get(function () {
    return true
})

现在,当我在 nodeJS 中使用 find 查询时,如下所示:

model.find({"$license_id": license_id})

结果,我有虚拟字段 show

但是

如果我像这样使用带有 aggregation 的查询:

model.aggregate([
    {
        $match: {
            $expr: { $eq: ["$license_id", license_id] }
        }
    }
])

结果,我没有虚拟字段show

如何获取 aggregation 查询中的虚拟字段? 你有解决这个问题的想法吗?

您可以使用 $addFields or $project stages to include the field in aggregation. Virtuals 未保存在数据库中的属性。您必须尝试一个函数才能获得所需的值。

model.aggregate([
    {
        $match: {
            $expr: { $eq: ["$license_id", license_id] }
        }
    },
   $addFields: {
        show: true
    }
])