【发布时间】:2021-12-28 23:40:13
【问题描述】:
我的userSchema 中有role 和user 和admin,但我不确定如何创建一个静态方法来根据用户是admin 还是返回所有文档user.
我确实尝试了以下...
userSchema.statics.findByRole = function (role) {
return this.find({ role: role });
};
但这没有用。
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
firstName: {
type: String,
},
lastName: {
type: String,
},
email: {
type: String,
required: [true, 'Please provide a valid email address!'],
unique: true,
lowercase: true,
},
password: {
type: String,
required: [true, 'Password is required!'],
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user',
},
createdAt: {
type: Date,
default: Date.now,
},
});
userSchema.virtual('fullName').get(function () {
return this.firstName + ' ' + this.lastName;
});
userSchema.statics.findByRole = function (role) {
return this.find({ role: role });
};
const User = mongoose.model('User', userSchema);
module.exports = User;
【问题讨论】:
-
find是异步的,你可能需要await
标签: node.js mongodb mongoose static-methods