首页 > 解决方案 > 架构中的属性值采用默认值而不是 MongoDB/Mongoose 中定义的值

问题描述

我的架构定义

const users = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Name is mandatory'],
  },
  email: {
    type: String,
    required: [true, 'Email is mandatory'],
    unique: true,
    validate: [validator.isEmail, 'Invalid Email Format'],
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user',
  },
  password: {
    type: String,
    required: [true, 'Password is mandatory'],
    minlength: 10,
    select: false,
  },
  confirmPassword: {
    type: String,
    required: [true, 'Confirming Password is mandatory'],
    validate: {
      validator: function (current) {
        return current === this.password;
      },
      message: 'Passwords do not match',
    },
  },
  createdAt: Date,
});

使用这个模式,我建立了一个控制器和路由机制来注册新用户,从 Postman 我发送带有正文的 post 请求:

{
    "name": "Postman",
    "email": "postman@post.com",
    "password": "postman999",
    "passwordConfirm": "postman999",
    "role": "admin",
    "createdAt": "2020-03-12"
}

以下是回复

{
    "status": "success",
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVlZDUyNzExMWFhOTJjNzE5ZDI2ODQ5YSIsImlhdCI6MTU5MTAyNzQ3NCwiZXhwIjoxNTk4ODAzNDc0fQ.IgH3D6l9Gk3JmXaLE_PSp6LsZzufqKEbMT-CVSsfLSU",
    "data": {
        "user": {
            "role": "user",
            "_id": "5ed527111aa92c719d26849a",
            "name": "Postman",
            "email": "postman@post.com",
            "password": "$2a$12$8dx7QwK4ShTWVuvEBV6qdOX7HA1I9TD9woDhF9W6kaBfEFaWuh2gW",
            "__v": 0
        }
    }
}

即使角色属性的值被显式定义为“ admin ”,架构定义的默认值也被保存在数据库中而不是显式定义的值,并且createdAt属性即使指定了值,也根本不会保存在数据库中。当“required: true”被添加到createdAtrole属性中的任何一个时,它会抛出一个错误,说“用户验证失败:角色:路径role是必须的。”

标签: node.jsmongodbexpressmongoosepostman

解决方案


推荐阅读