You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Mongoose的find()方法查询包含指定枚举值的数组字段?

解决方案

首先得把Schema里的roles字段类型改成Array,才能存储多角色组合:

const User = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    mobile: {
        type: Number,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    roles: {
        type: Array, // 改为数组类型
        required: true,
        enum: ["admin", "user", "student", "instructor"],
        default: ["user"], // 默认值同步改为数组格式
    }
});

查询包含"student"角色的用户

有几种实用的写法:

  1. 直接匹配数组元素
    Mongoose对数组字段支持直接匹配元素,只要数组里包含该值就会被筛选出来,这是最简洁的写法:
const students = await User.find({ roles: "student" });
  1. 使用$in操作符(适配多值查询场景)
    如果之后需要同时匹配多个角色(比如找包含student或instructor的用户),$in会更灵活,单值查询也完全适用:
const students = await User.find({ roles: { $in: ["student"] } });
  1. 使用$elemMatch(复杂条件场景用)
    如果需要对数组元素做更精细的条件判断(比如结合其他字段规则),可以用$elemMatch,不过单值匹配的话没必要:
const students = await User.find({ roles: { $elemMatch: { $eq: "student" } } });

注意事项

如果数据库里已有旧数据(roles是String类型),需要先做数据迁移,把单角色字符串转成数组格式,比如把"student"更新为["student"],否则旧数据无法被查询匹配到。

内容的提问来源于stack exchange,提问作者Koladee1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 19:12:36