Count documents with some conditions on subdocuments with mongoose

Viewed 27

I have this code

const filterOptions: CCFilterOptions = {
    filter: {
        $and: [
            { _id: req.params.id, isDeleted: false },
            { $or: [{ owner: uid }, { $and: [{ 'partners.user': uid, 'partners.canEdit': true }] }] },
        ],
    },
    options: {
        limit: 1,
    },
};

const count = await creditCardServices.countCreditCardsByFilter(filterOptions);

My problem is that if I have a Credit Card where the uid is a partner and its value of 'canEdit' is false, but in these Credit Card there are other partner with different user id (parner.user !== uid) but its 'canEdit' value is true, the final count value is 1 but must to be 0.

What I'm doing wrong in the query?

I'm working with Express and TypeScript, this is the function 'countCreditCardsByFilter':

export const countCreditCardsByFilter = async (filterOptions: CCFilterOptions): Promise<number> => {
    const { filter = {}, options = {} } = filterOptions;
    try {
        return await CreditCard.countDocuments(filter, options);
    } catch (err) {
        throw new Error(`${err}`);
    }
};

Thanks a lot!

0 Answers
Related