【问题标题】:Mongoose: validation error path is requiredMongoose:需要验证错误路径
【发布时间】:2015-07-27 21:30:22
【问题描述】:

我正在尝试使用 mongoose 在 mongodb 中保存一个新文档,但即使我提供了电子邮件、密码哈希和用户名,我也会收到 ValidationError: Path 'email' is required., Path 'passwordHash' is required., Path 'username' is required.

这是用户架构。

    var userSchema = new schema({
      _id: Number,
      username: { type: String, required: true, unique: true },
      passwordHash: { type: String, required: true },
      email: { type: String, required: true },
      admin: Boolean,
      createdAt: Date,
      updatedAt: Date,
      accountType: String
    });

这就是我创建和保存用户对象的方式。

    var newUser = new user({

      /* We will set the username, email and password field to null because they will be set later. */
      username: null,
      passwordHash: null,
      email: null,
      admin: false

    }, { _id: false });

    /* Save the new user. */
    newUser.save(function(err) {
    if(err) {
      console.log("Can't create new user: %s", err);

    } else {
     /* We succesfully saved the new user, so let's send back the user id. */

    }
  });

那么为什么mongoose会返回验证错误,我可以不使用null作为临时值吗?

【问题讨论】:

  • 好吧,我看不到您在哪里设置 newUsers 电子邮件、passwordHash 和用户名。您将它们设置为 null 然后尝试保存它。
  • 你不能那样做吗? null 是一个值。
  • 我正在搜索同样的问题。原来我这样做了 create({ ...stuff }, { new: true })... 选项不好!

标签: javascript node.js mongodb mongoose


【解决方案1】:

回应您的最后评论。

你说得对,null 是一个值类型,但 null 类型是一种告诉解释器它有 没有值的方式。因此,您必须将值设置为任何非空值,否则会出现错误。在您的情况下,将这些值设置为空字符串。即

var newUser = new user({

  /* We will set the username, email and password field to null because they will be set later. */
  username: '',
  passwordHash: '',
  email: '',
  admin: false

}, { _id: false });

【讨论】:

【解决方案2】:

嗯,以下是我摆脱错误的方法。我有以下架构:

var userSchema = new Schema({
    name: {
        type: String,
        required: 'Please enter your name',
        trim: true
    },
    email: {
        type: String,
        unique:true,
        required: 'Please enter your email',
        trim: true,
        lowercase:true,
        validate: [{ validator: value => isEmail(value), msg: 'Invalid email.' }]
    },
    password: {
        type: String/
        required: true
    },
    // gender: {
    //     type: String
    // },
    resetPasswordToken:String,
    resetPasswordExpires:Date,
});

我的终端向我抛出以下日志,然后在调用我的注册函数时进入无限重新加载:

(node:6676) UnhandledPromiseRejectionWarning: 未处理的承诺 拒绝(拒绝 id:1):ValidationError:密码:路径 password 为必填项,邮箱:无效邮箱。

(node:6676) [DEP0018] DeprecationWarning: 未处理的承诺拒绝 已弃用。将来,未处理的承诺拒绝 将使用非零退出代码终止 Node.js 进程。

因此,正如它所说的 Path 'password' is required,我在我的模型中注释了 required:true 行和我的模型中的 validate:email 行。

【讨论】:

    【解决方案3】:

    我在寻找相同问题的解决方案时遇到了这篇文章 - 即使值已传递到正文中,也会出现验证错误。 原来我错过了 bodyParser

    const bodyParser = require("body-parser")
    
    app.use(bodyParser.urlencoded({ extended: true }));
    

    我最初没有包含 bodyParser,因为它应该包含在最新版本的 express 中。添加以上 2 行解决了我的验证错误。

    【讨论】:

      【解决方案4】:

      我遇到了同样的错误,所以我所做的是我的模型中需要的任何字段,我必须确保它出现在我的服务或您拥有的任何地方的新用户 Obj 中

      const newUser = new User({
          nickname: Body.nickname,
          email: Body.email,
          password: Body.password,
          state: Body.state,
          gender:Body.gender,
          specialty:Body.specialty
      });
      

      【讨论】:

        【解决方案5】:

        对我来说,快速而肮脏的解决方法是从我的输入表单字段中删除 encType="multipart/form-data"

        之前,<form action="/users/register" method="POST" encType="multipart/form-data">
        并且,在<form action="/users/register" method="POST">

        之后

        【讨论】:

          【解决方案6】:

          基本上,您这样做是正确的,但是如果您添加引导程序或任何其他库元素,它们已经有了验证器。 因此,您可以从 userSchema 中删除验证器。

          在这里,在手机属性中,您可以删除“required: true”,因为它已经在引导程序和其他库/依赖项中进行了检查。

          var userSchema = new Schema({
          name: {
              type: String,
              required: 'Please enter your name',
              trim: true
          },
          phone: {
              type: number,
              required: true
          } });
          

          【讨论】:

            【解决方案7】:

            解决此类错误

            ValidationError: Path 'email' is required.
            

            您的电子邮件在 Schema 中设置为必需,但没有给出值或电子邮件字段未添加到模型上。

            如果您的电子邮件值可能为空,请在模型中设置默认值或在验证器中设置允许(“”)。 喜欢

             schemas: {
                notificationSender: Joi.object().keys({
                    email: Joi.string().max(50).allow('')
                })
              }
            

            我认为会解决这类问题。

            【讨论】:

              【解决方案8】:

              我也遇到了同样的错误

              import mongoose from 'mongoose';
              
              const orderSchema = mongoose.Schema(
                {
                  user: {
                    type: mongoose.Schema.Types.ObjectId,
                     required: true,
                    ref: 'User',
                  },
                  orderItems: [
                    {
                      name: { type: String, required: true },
                      qty: { type: Number, required: true },
                      image: { type: String, required: true },
                      price: { type: Number, required: true },
                      product: {
                        type: mongoose.Schema.Types.ObjectId,
                        required: true,
                        ref: 'Product',
                      },
                    },
                  ],
                  shippingAddress: {
                    address: { type: String, required: true },
                    city: { type: String, required: true },
                    postalCode: { type: String, required: true },
                    country: { type: String, required: true },
                  },
                  paymentMethod: {
                    type: String,
                    required: true,
                  },
                  paymentResult: {
                    id: { type: String },
                    status: { type: String },
                    update_time: { type: String },
                    email_address: { type: String },
                  },
                  taxPrice: {
                    type: Number,
                    required: true,
                    default: 0.0,
                  },
                  shippingPrice: {
                    type: Number,
                    required: true,
                    default: 0.0,
                  },
                  totalPrice: {
                    type: Number,
                    required: true,
                    default: 0.0,
                  },
                  isPaid: {
                    type: Boolean,
                    required: true,
                    default: false,
                  },
                  paidAt: {
                    type: Date,
                  },
                  isDelivered: {
                    type: Boolean,
                    required: true,
                    default: false,
                  },
                  deliveredAt: {
                    type: Date,
                  },
                },
                {
                  timestamps: true,
                }
              );
              
              const Order = mongoose.model('Order', orderSchema);
              
              export default Order;
              

              下面是我终端中的错误:

              消息:“订单验证失败:用户:需要路径 user。”

              我所做的只是从用户那里删除 required 并且一切正常。

              【讨论】:

              • 这不是解决方案,如果这是一个必需的嵌套字段,它应该保持这样。
              【解决方案9】:

              您只需添加 app.use(express.json()); 即可正常工作。

              【讨论】:

                猜你喜欢
                • 2020-08-20
                • 2021-10-17
                • 2022-10-14
                • 2014-05-09
                • 2022-06-29
                • 2022-12-14
                • 2019-11-30
                • 2011-04-18
                • 1970-01-01
                相关资源
                最近更新 更多