0

I'm writing a REST API in Node.js using Mongoose to access the MongoDB backend database. I want to provide an API endpoint that returns a count of the number of array objects that match a particular variationStatus.

This is what I have so far but it gives me an empty response...

//Get 'Approved' count
app.get("/v1/approvedcount", async (request, response) => {
    var status = 'Approved';
    try {
        var result = await variationsModel.find({ 'variations.variationStatus': status }).exec().count();
        response.send(result);
    } catch (error) {
        response.status(500).send(error);
    }
} )

And this is my model...

const variationsModel = mongoose.model("variations", {
    "variations": [
        {
        "variationID": String,
        "custID": String,
        "projID": String,
        "variationTitle": String,
        "variationDesc": String,
        "variationStatus": String,
        "variationChargeable": String,
        "variationCost": String,
        "requireMaterial": String,
        "variationRequestor": String,
        "variationCreationDate": String,
        "variationImages": [
            {
            "imageId": String
            }
        ],
        "variationCategory": String
        }
    ]
});

Anyone help me out?

Thanks!

Octo
  • 93
  • 8

1 Answers1

0

You can use MongoDB aggregation pipeline to achieve the same.

Try this:

variationsModel
    .aggregate([{
         $match : {
            'variations.variationStatus' : status
         }
    },{
        $unwind : "variations"
    },{
        $match : {
            'variations.variationStatus' : status
        }
    },{
        $group : {
            _id : "$_id",
            variations : {
                $push : '$variations'
            }
        }
    },{
        $project : {
            count : {$size : $variations}
        }
    }]);

Explanation:

  1. $match : To only select those documents which have atleast one element in variations array with variationStatus : status

  2. $unwind : To expand the variations array and convert it from array to object. $unwind creates multiple documents from single document, with individual array elements, and all the other field remains same.

  3. $match : To select only those documents which has variations.variationStatus:status

  4. $group : Group all the documents back into original form (group with _id), and create variations array again, but this time it will only contain those elements with variationStatus :status

  5. $project : This step is specifically to count the size of variations array , using $size.

For detailed info, please read MongoDb $unwind , $project and $size documentation.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52