0

I'm trying to do an aggregation query to the db for objects with a specific id, and sum it all up and as well give me an average.

My Scenario

I've a model that looks like this:

attributes: {

    user: {
        model: 'user',
        required: true
    },

    rating: {
        type: 'integer',
        enum: [0, 1, 2, 3, 4, 5],
        defaultsTo: 0,
        required: true
    },

    inventory: {
        model: 'subItem'
    },

    size: {
        model: 'size',
        required: true
    },

    isDeleted: {
        type: 'boolean',
        defaultsTo: false
    }
}

Aggregating for the average rating like this:

const aggQuery = [
    {
        $match: {"size" : theRating.data[0].size, "isDeleted": false}
    },
    {
        $group: {
            _id: "$size",
            total: { $sum: 1 },
            average: { $avg: "$rating" }
        }
    }
]

My Function

module.exports = {

    aggregateQuery: (model, aggregate) => {
        return new Promise((resolve, reject) => {

            model.native(function (err, collection) {
                if (err) return reject(err);

                collection.aggregate(aggregate, function (err, result) {
                    if (err) return reject(err);

                    return resolve(result);
                })
            })
        })
    }
}

Use Case I populate the db with 16 records while writing the test, but, after running the aggregate query, I get an empty array

NativeQueryService.aggregateQuery(Rating, aggQuery).then(result => {
    console.log(result)
}).catch(err => {
    console.log(err)
})

Any help on what I'm doing wrong would be appreciated. Thanks.

9
  • The aggregation query looks good. Check for obvious things like collection name, query filter and input values. Commented Mar 5, 2017 at 22:29
  • is your 'size' field an ObjectId or an embedded document? Commented Mar 5, 2017 at 22:34
  • It's an ObjectID @leonziyo Commented Mar 5, 2017 at 22:35
  • can you confirm theRating.data[0].size is also an ObjectId and not a document (object)? Commented Mar 5, 2017 at 22:43
  • 1
    there it is, you are passing a string instead of an ObjectId, it should be ObjectId('58bc93f08efcbf950019ef1b') instead of '58bc93f08efcbf950019ef1b' Commented Mar 5, 2017 at 22:49

1 Answer 1

1

Make sure to pass a valid ObjectId and not a string to your $match stage.

{
    $match: {"size" : ObjectId(theRating.data[0].size), "isDeleted": false}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.