我在我的userSchemafor rolea 中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;
uj5u.com熱心網友回復:
對于 find、findOneAndUpdate 等,你應該使用 async/await;因為連接到資料庫可能很耗時。
userSchema.statics.findByRole = async function (role) {
await this.find({ role: role })
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360476.html
