【问题标题】:Mongo DB: ValidationError: User validation failed: username: Path `username` is requiredMongo DB:ValidationError:用户验证失败:用户名:需要路径“用户名”
【发布时间】:2021-11-30 01:12:00
【问题描述】:

当我尝试使用 Mongoose 将新文档(用户)保存/创建到 Mongo DB 时,尽管为所有值提供了正确的 DataType,但我收到以下验证错误:

ValidationError:用户验证失败:用户名:路径用户名是必需的。

我是 Node JS 和 Mongo DB 的初学者。因此,我无法理解出了什么问题。

我还添加了以下模块:

快递 蒙哥 猫鼬

详细错误

enter image description here

用户架构/模型

enter image description here

用户控制器

enter image description here

我只是不明白,为什么我会收到此验证错误。任何人都可以指导我完成这个。感谢您的帮助。

【问题讨论】:

  • 请勿粘贴图片,请使用格式化文本

标签: node.js mongodb express mongoose


【解决方案1】:

这是因为在发布请求中您没有填写用户名字段,为什么会发生这种情况: 它可能是其中之一:

  1. 您没有在前端输入名称标签
  2. 你把名字复制错了(req.body.[wrongname])
  3. 您错误地将名称添加到数据库中。 new userModel({username: [wrong data]})

我会给你一个例子,用 node 发送用户名到 mongo。

  1. 你应该安装bodyParsermongoose (npm I body-parser, npm I mongoose)
  2. 考虑下面的代码
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
  extended: false
}))
app.use(bodyParser.json())
let userSchema = new mongoose.Schema({
  username: {
    type: String
  }
})

let userModel = new mongoose.Model('users', userSchema);
app.get('/signup', (req, res) => {
  res.render('signup')
})

app.post('/signup', (req, res) => {
  const username = req.body.username;
  let newUser = new userModel({
    username: username
  })
  newUser.save(function (err, doc) {
    res.send(doc)
  });
})

【讨论】:

    猜你喜欢
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2020-11-26
    • 2019-11-30
    • 2022-01-17
    • 2022-01-21
    相关资源
    最近更新 更多