如何将我的架构中的管理员角色数量限制为一个?

问题描述 投票:0回答:1

schema.js

const userSchema = new mongoose.Schema({
  role: {
    type: String,
    enum: ["user", "admin"],
    default: "user",
  },
})

我想设置一个规则,一次只能存在 1 个管理员。我想我可能需要使用自定义验证器,但不确定是否有更好的方法。

node.js mongodb express mongoose
1个回答
0
投票

要将 MongoDB 架构中的管理员角色数量限制为一个,您可以结合使用唯一索引和验证函数。以下是如何修改

userSchema
的示例:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user',
  },
});

userSchema.index({ role: 1 }, { unique: true, partialFilterExpression: { role: 'admin' } });

// Add a pre-save hook to validate the number of admin roles
userSchema.pre('save', async function (next) {
  if (this.isModified('role') && this.role === 'admin') {
    const isAdmin = await this.model('User').findOne({ role: 'admin' });

    if (isAdmin && !isAdmin._id.equals(this._id)) {
      const error = new Error('Admin is exist!!.');
      return next(error);
    }
  }

  next();
});

const User = mongoose.model('User', userSchema);

module.exports = User;

我希望这对你有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.