【问题标题】:Mongoose ValidationError (Path is required)Mongoose ValidationError(路径是必需的)
【发布时间】:2020-07-06 01:25:37
【问题描述】:

我正在尝试在 express 中编写一个 post 方法...对于一些计划 web 应用程序的事件... 创建了事件模型和用户模型,在事件模型中传递了一个 id 字段......在此之后我的代码停止工作......给了我上述错误...... 我附上屏幕截图

任何帮助将不胜感激

我正在尝试在 express 中编写一个 post 方法...对于一些计划 web 应用程序的事件... 创建了事件模型和用户模型,在事件模型中传递了一个 id 字段......在此之后我的代码停止工作......给了我上述错误...... 我附上屏幕截图

任何帮助将不胜感激

我正在尝试在 express 中编写一个 post 方法...对于一些计划 web 应用程序的事件... 创建了事件模型和用户模型,在事件模型中传递了一个 id 字段......在此之后我的代码停止工作......给了我上述错误...... 我附上屏幕截图

任何帮助将不胜感激

//Event Model
const mongoose = require('mongoose');
const eventSchema = new mongoose.Schema({
   title:{
       type:String,
       required:true
   },

   description:{
       type:String,
       required:true
   },
   location:{
       type:String,
       required:true
   },
   date:{
       type:Date,
       required:true,
       default:Date.now
   },
user_id:{
    type:String,
    required:true
     },

   created_at:{
       date:Date,
   }
});
const Event = mongoose.model('Event',eventSchema,'events');
module.exports = Event;



//User Model
const mongoose = require('mongoose');
const bCrypt = require('bcrypt-nodejs');
const userSchema = new mongoose.Schema({
   email:{
       type:String,
       required:true
   },
   password:{
       type:String,
       required:true
   }
});
userSchema.methods.hashPassword = (password) =>{
   return bCrypt.hashSync(password,bCrypt.genSaltSync(10))
}
userSchema.methods.comparePasswords = (password,hash)=>{
   return bCrypt.compareSync(password,hash);
}

const User = mongoose.model('User',userSchema,'users');

module.exports = User;





//post Method:

router.post('/create',[
   check('title').isLength({min:5}).withMessage('Title should be more than 5 letters'),
   check('description').isLength({min:5}).withMessage('description should be more than 5 letters'),
   check('location').isLength({min:5}).withMessage('location should be more than 5 letters'),
   check('date').isLength({min:5}).withMessage('date should be more than 5 letters')
  ],(req,res)=>{
       const errors = validationResult(req);
       if(!errors.isEmpty()){
           req.flash('errors',errors.array())
           res.redirect('/events/create')
       }
       else{
           const newEvent = new Event({
               title:req.body.title,
               description:req.body.description,
               location:req.body.location,
               date:req.body.date,
               user_id:req.user_id,
               created_at:Date.now()
           });
           newEvent.save((err)=>{
               if(!err){
                   console.log('Event was added!');
                   req.flash('info','Event was created successfully!');
                   res.redirect('/events');
               }
               else{
                   console.log(err);
               }
           })
       }
  }); 




App is running on port 3000
(node:23844) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
Error [ValidationError]: Event validation failed: user_id: Path `user_id` is required.
   at ValidationError.inspect (C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\error\validation.js:61:24)
   at formatValue (internal/util/inspect.js:563:31)
   at inspect (internal/util/inspect.js:221:10)
   at formatWithOptions (internal/util/inspect.js:1693:40)
   at Object.Console.<computed> (internal/console/constructor.js:272:10)
   at Object.log (internal/console/constructor.js:282:61)
   at C:\Users\Hassan\Desktop\events\routes\event-routes.js:69:29
   at C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\model.js:4598:16
   at C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\utils.js:256:11
   at C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\model.js:468:16
   at C:\Users\Hassan\Desktop\events\node_modules\kareem\index.js:246:48
   at next (C:\Users\Hassan\Desktop\events\node_modules\kareem\index.js:167:27)
   at next (C:\Users\Hassan\Desktop\events\node_modules\kareem\index.js:169:9)
   at Kareem.execPost (C:\Users\Hassan\Desktop\events\node_modules\kareem\index.js:217:3)
   at _handleWrapError (C:\Users\Hassan\Desktop\events\node_modules\kareem\index.js:245:21)
   at C:\Users\Hassan\Desktop\events\node_modules\kareem\index.js:272:14 {
 errors: {
   user_id: MongooseError [ValidatorError]: Path `user_id` is required.
       at new ValidatorError (C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\error\validator.js:29:11)
       at validate (C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\schematype.js:1055:13)
       at C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\schematype.js:1109:11
       at Array.forEach (<anonymous>)
       at SchemaString.SchemaType.doValidate (C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\schematype.js:1064:14)
       at C:\Users\Hassan\Desktop\events\node_modules\mongoose\lib\document.js:2190:9
       at processTicksAndRejections (internal/process/task_queues.js:75:11) {
     message: 'Path `user_id` is required.',
     name: 'ValidatorError',
     properties: [Object],
     kind: 'required',
     path: 'user_id',
     value: undefined,
     reason: undefined,
     [Symbol(mongoose:validatorError)]: true
   }
 },
 _message: 'Event validation failed',
 name: 'ValidationError'
}
connected to DB



```````````````````````````````````````````````````````````````````
``````````````````````````````````````````````````````````````````````````
i am trying to write a post method in express...for some events planing web app...
created the event model and the user model, passed an id field in the event model...after this my code stopped working...giving me the above error...
i am attaching screen shots 


any help would be appreciated 

【问题讨论】:

  • 能否在问题中添加型号、路由器等相关代码?
  • 已添加...谢谢
  • 可以删除Events集合中的集合试试吗?因为您添加了必需的 userId 字段,但以前的文档在此之前没有此字段。
  • 嗨 ...我从我的收藏中删除了事件集合并重试了....仍然收到相同的错误:我在问题正文中添加了完整的错误日志供您参考....谢谢很多
  • 我想我找到了问题,你能检查我的答案吗?

标签: node.js express mongoose


【解决方案1】:

这是 mongoose 错误,主要是由于 mongoose 连接未找到 POST 或 GET API 的 URL。

  1. 另一个机会是确保您已使用 bin 在 mongoose 安装位置创建 /data 文件夹,并启动 Mongoose 和 mongod.exe 的 mongoose 服务,并尝试使用 Mongodb compass 来检查连接是否成功。

  2. 其他如检查您的 Mongo 连接是否连接正确,如果它已连接或未在 DB 连接 URL 中。

【讨论】:

  • 你好......连接完全正常......我正在使用mongo atlas......我在添加user_id字段之前发布的所有帖子都是成功的......错误才开始显示我何时在事件模型和 post 方法中添加了 user_id 字段
  • 您说 null 是值类型是正确的,但 null 类型是告诉解释器它没有值的一种方式。因此,您必须将值设置为任何非空值,否则会出现错误。在您的情况下,将这些值设置为空字符串。
  • var newUser = new user({ /* 我们将设置用户名、电子邮件和密码字段为空,因为它们稍后会设置。*/ username: '', passwordHash: '', email: '',管理员:假},{_id:假});
猜你喜欢
  • 2020-08-20
  • 2020-02-28
  • 1970-01-01
  • 2019-09-11
  • 2016-10-30
  • 2021-12-10
  • 2020-06-10
  • 2021-01-17
  • 2021-04-19
相关资源
最近更新 更多