繁体   English   中英

如何计算 mongoose 中参考中有字段的元素?

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

我需要计算有多少元素具有您的引用类型具有的属性,例如:

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,
        },
    },
);

我想计算有多少工人是活跃的(活跃:真),按公司名称搜索。

我已经尝试过:

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

但是,计算所有工作人员并填充匹配的人员(我只需要计算匹配项)。

和:

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

但不起作用:(

谁能帮我?

我用 $lookup 解决。 https://docs.mongodb.com/master/reference/operator/aggregation/lookup/

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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