【问题标题】:Static method for filtering all documents based on property of enum type基于枚举类型属性过滤所有文档的静态方法
【发布时间】:2021-12-28 23:40:13
【问题描述】:

我的userSchema 中有roleuseradmin,但我不确定如何创建一个静态方法来根据用户是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


【解决方案1】:

对于 find、findOneAndUpdate 等,您应该使用 async/await;因为连接到数据库可能很耗时。

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

【讨论】:

  • 谢谢,我是根据@Joe 评论做到的。但我才意识到我没有返回任何东西,这是我的问题!不过感谢您的回复。
猜你喜欢
  • 2019-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
相关资源
最近更新 更多