为了账号安全,请及时绑定邮箱和手机立即绑定

Mongoose 在架构级别排除文档结果

Mongoose 在架构级别排除文档结果

慕婉清6462132 2023-09-07 16:36:13
我正在为我的用户创建一个模型。每个用户都有一个isVerified布尔值属性。我希望能够调用Model.find猫鼬模型并排除所有文档,而isVerified === false不必在查询期间指定这一点。我想在架构中设置它,以便每当Model.find调用时这些文档都会自动排除。任何帮助表示赞赏用户模型:const UserSchema:Schema = new Schema({    name: {        type: String,        required: true,        trim: true,    },    email: {        type: String,        required: true,        unique: true,        lowercase: true,        trim: true,        index: true,        validate: {            validator: (value:string) => validator.isEmail(value),            message: (props:any) => "Invalid Email Address"        },    },    password: {        type: String,        trim: true,        required: true,        select: false,        minlength: 6,        validate: {            validator: (value:string) => !validator.contains(value, "password"),            message: (props:any) => "Your password cannot contain the word 'password'"        }    },    phoneNumber: {        type: String,        trim: true,        required: true,        validate: {            validator: (value:string) => validator.isMobilePhone(value, 'any', {strictMode: true}),            message: (props:any) => "Please include country code (e.g. +233 for Ghana +44 for the United Kingdom) to phone number"        }    },    isActive: {        type: Boolean,        default: false    }    ,    tokens: [        {            token: {                type: String,                required: true            }        }    ]},{    strict: "throw",    timestamps: true})编辑:我做了一些挖掘,看来我可以覆盖基本方法来重新实现返回的查询。我尝试这样做,如下所示:UserSchema.statics.find = function () {    let query = UserModel.find.apply(this, arguments);    query.where('isActive').ne(false)    return query;}但是我收到以下错误 RangeError: Maximum call stack size exceeded
查看完整描述

1 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

终于想通了。需要将更改应用于Model对象而不是实例,UserModel如下所示:


UserSchema.statics.find = function () {

    let query = Model.find.apply(this, arguments);

    query.where('isActive').ne(false)

    return query;

}

现在 find 方法会跳过不活动的用户


查看完整回答
反对 回复 2023-09-07
  • 1 回答
  • 0 关注
  • 52 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信