简体   繁体   中英

How to count elements that have a field in your reference in mongoose?

I need to count how many elements have an property that your reference type have, example:

const workerSchema = new Schema(
    {
        userId: {
            type: Types.ObjectId,
            ref: 'User',
            required: true,
        },
        active: {
            type: Boolean,
            required: true,
        },
    }
);

const userSchema = new Schema(
    {
        name: {
            type: String,
            required: true,
        },
        company: {
            type: String,
            required: true,
        },
    },
);

I want to count how many Workers is active (active: true), search by the company name.

I already try:

Worker.find({ active: true })
    .populate({
        path: 'userId',
        match: { company: 'name' },
    })
    .countDocuments();

But this, count all workers and populate who match (i need to count only the matches).

And:

Worker.find({
    'userId.company': 'name',
    active: true,
});

But doesn't work:(

Can anyone help me?

I solve with $lookup. https://docs.mongodb.com/master/reference/operator/aggregation/lookup/

$lookup: {
    from: 'users',
    localField: 'userId',
    foreignField: '_id',
    as: 'allUsers',
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM