如何修复“ValidationError:用户验证失败:名称:需要路径‘name’。” Mongo 错误?

编程入门 行业动态 更新时间:2024-10-03 14:22:25

如何修复“ValidationError:用户验证失败:名称:需要<a href=https://www.elefans.com/category/jswz/34/1771438.html style=路径‘name’。” Mongo 错误?"/>

如何修复“ValidationError:用户验证失败:名称:需要路径‘name’。” Mongo 错误?

我正在创建一个新用户并检查用户电子邮件以前是否存在。如果不是,那么它正在创建一个新用户并保存它。我需要什么来纠正我得到的这个验证错误?

我已经尝试过将名称设置为不需要。但它仍然不起作用。

这是我的用户模型。

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

//Declaring User Model
const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  avatar: {
    type: String
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = User = mongoose.model("users", UserSchema);

这是用户路线。

router.post("/register", (req, res) => {
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      return res.status(400).json({ email: "email already exists" });
    } else {
      const avatar = gravatar.url(req.body.email, {
        s: "200", //size
        r: "pg", //rating
        d: "mm" //default
      });
      const newUser = new User();
      const newUser = {
        name: req.body.name,
        email: req.body.email,
        avatar,
        password: req.body.password
      };
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(newUser.password, salt, (err, hash) => {
          if (err) throw err;
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => console.log(err));
        });
      });
    }
  });
});

我期待它被存储。这是我得到的错误。

{ ValidationError: users validation failed: name: Path `name` is required.
    at ValidationError.inspect (G:\devconnector\node_modules\mongoose\lib\error\validation.js:59:24)
    at formatValue (internal/util/inspect.js:493:31)
    at inspect (internal/util/inspect.js:191:10)
    at Object.formatWithOptions (util.js:84:12)
    at Console.(anonymous function) (console.js:191:15)
    at Console.log (console.js:202:31)
    at newUser.save.then.catch.err (G:\devconnector\routes\api\users.js:39:35)
    at process._tickCallback (internal/process/next_tick.js:68:7)
  errors:
   { name:
      { ValidatorError: Path `name` is required.
          at new ValidatorError (G:\devconnector\node_modules\mongoose\lib\error\validator.js:29:11)
          at validate (G:\devconnector\node_modules\mongoose\lib\schematype.js:1034:13)
          at G:\devconnector\node_modules\mongoose\lib\schematype.js:1088:11
          at Array.forEach (<anonymous>)
          at SchemaString.SchemaType.doValidate (G:\devconnector\node_modules\mongoose\lib\schematype.js:1043:14)
          at G:\devconnector\node_modules\mongoose\lib\document.js:2133:9
          at process._tickCallback (internal/process/next_tick.js:61:11)
          message: 'Path `name` is required.',
          name: 'ValidatorError',
          properties: [Object],
          kind: 'required',
          path: 'name',
          value: undefined,
          reason: undefined,
          [Symbol(mongoose:validatorError)]: true } },
          _message: 'users validation failed',
          name: 'ValidationError' }
回答如下:

在您的代码中,我可以看到您将

newUser
设置为 User() 模型对象,然后将其设置为普通的 javascript 对象。这在语法上也是错误的。

基本上你需要用这些值制作模型对象。

const newUser = new User({
   name: req.body.name,
   email: req.body.email,
   avatar,
   password: req.body.password
});

更多推荐

如何修复“ValidationError:用户验证失败:名称:需要路径‘name’。” Mongo 错误?

本文发布于:2024-05-30 04:37:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770162.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   错误   名称   用户   ValidationError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!