mongodb 如何修复“验证错误:用户验证失败:name:路径'name'是必需的,'Mongo错误?

yhived7q  于 2022-12-18  发布在  Go
关注(0)|答案(5)|浏览(155)

我正在创建一个新用户,并检查该用户的电子邮件以前是否存在。如果不存在,则正在创建一个新用户并保存它。我需要做什么来更正我遇到的验证错误?
我已经尝试过将名称设置为不需要的。但它仍然不起作用。
这是我的用户模型。

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' }

mzaanser

mzaanser1#

在你的代码中,我可以看到你把newUser设置为User()模型对象,然后把它设置为一个普通的javascript对象,这在语法上也是错误的。
基本上,您需要使用这些值创建模型对象。

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

ssm49v7z2#

解决方案非常简单,现在和将来都可以避免使用额外参数,因为您不需要它们

const userSchema = mongoose.Schema({
    email: String,
    username: String,
    password: String,
    googleId:   String,
    avatar_url: String,
});
yr9zkbsy

yr9zkbsy3#

遇到类似问题,通过在app.js中添加以下行解决:

app.use(
    express.urlencoded({ extended: true })
);
    
app.use(express.json());
wgmfuz8q

wgmfuz8q4#

确保API post主体包含正确的json键和值对,以便按照mongoose模型创建新文档。

e0bqpujr

e0bqpujr5#

上述问题将被清除时,您设置的内容类型为应用程序或json在后的人,然后你可以检查它,将正常工作与出产生的错误,我已经面对上述错误,我做同样的它修复了我的问题。

相关问题