【发布时间】:2021-03-09 16:44:18
【问题描述】:
我正在为我的用户创建一个模型。每个用户都有一个属性isVerified,它是一个布尔值。我希望能够在 mongoose 模型上调用 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
【问题讨论】:
标签: javascript node.js arrays mongoose nosql