Home > Software design >  Mongoose projection to filter list not working, but native does
Mongoose projection to filter list not working, but native does

Time:01-05

I'm trying to use the following find query to find a list of objects which are related to a "work" object with a specific ID, then return all "form" elements which aren't set to inactive (active = false).

This works perfectly using the mongo shell locally, or enter image description here

CodePudding user response:

try using aggregation for this

const objs = await ObjectModel.aggregate([
    {
        '$match': {
            work: mongoose.Types.ObjectId(workID),
            "form.active": false
        }
    }, {
        '$project': {
            form: {
                $filter: {
                    input: "$form",
                    as: "f",
                    cond: {
                        $ne: ["$$f.active", false],
                    },
                },
            },
        }
    }
])

include form.active key in match also as it will lessen the number of documents after match query only

  •  Tags:  
  • Related