简体   繁体   中英

Mongoose ValidationError (Path is required)

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

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

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

//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 

This is mongoose Error mostly due to mongoose connection not finding URL for POST or GET API.

  1. One other chance is to make sure you have created a /data folder inside your mongoose installation location with bin and start mongoose service which is Mongoose and mongod.exe and try with Mongodb compass for checking connection is successful or not.

  2. other like check your Mongo connection is connected properly if it is connected or not in DB connection URL.

You are trying to get userId from req.user_id.

it must from req.body.user_id like this:

 user_id:req.body.user_id,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM