Search code examples
node.jsmongodbmongoosemongodb-querymongoose-schema

how to get virtual fields in aggregation query in mongodb?


i have model with one virtual field show:

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

now, when I use query in nodeJS with find like this:

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

In result, I have the virtual field show.

but

if I use query with aggregation like this :

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

In result, I don't have the virtual field show.

how to get the virtual fields in aggregation queries? Do you have any idea to solve this problem?


Solution

  • You can use $addFields or $project stages to include the field in aggregation. Virtuals are properties not persisted in the database. You have to try a function to get the required value.

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