Home > Blockchain >  Static method for filtering all documents based on property of enum type
Static method for filtering all documents based on property of enum type

Time:11-19

I have in my userSchema for role a user and admin but I'm not sure how I can create a static method to return all documents based on if the user is an admin or user.

I did try the following...

userSchema.statics.findByRole = function (role) {
  return this.find({ role: role });
};

but that didn't work.

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;

CodePudding user response:

for find, findOneAndUpdate, etc you should use async/await; Because getting connected to the database can be time consuming.

userSchema.statics.findByRole = async function (role) {
  await this.find({ role: role })
}
  • Related