Mongoose schema validation atlas

29 views Asked by At

So I'm working on this project about the application that uses a MongoDB database to store data. In particular, instead of using a local MongoDB server, I will use MongoDB Atlas, which is a cloud database service. Further, the app will use Mongoose ODM to integrate the database.

I have everything in vscode.

I'm supposed to use postman for Error handling.

So in case of mongoose validation fails, a 400 error and validation errors should be display in postman. (post /events (use postman to send the request without any data)

I've implement all the code needed but I'm getting a "500 Error Internal Server Error" instead of "400 Event validation failed: image: Path 'image' is required. etc..."

This is a snippet code of what I did so far.

exports.create = (req, res, next) => {
    let event = new model(req.body);
    event.image = "/images/" + req.file.filename;
    event.validate((err) => {
        if(err && err.name === "ValidationError") { 
           err.status = 400;
           return next(err);
        }
        event.save()
            .then(event => res.redirect('/events'))
            .catch(err => next(err));
    });
};


exports.update = (req, res, next) => {
    let event = req.body;
    let id = req.params.id;


    if(!id.match(/^[0-9a-fA-F]{24}$/)) {
        let err = new Error('Invalid event id');
        err.status = 400;
        return next(err);
    }


    if (req.file) {
        event.image = "/images/" + req.file.filename;
    }
   
    event.id = req.params.id;


    model.findByIdAndUpdate(id, event, {useFindAndModify: false, runValidators: true})
    .then(event=>{
        if(event) {
            res.redirect('/events/'+id);
        } else {
            let err = new Error('Cannot find an event with id ' + id);
            err.status = 404;
            next(err);
        }
    })
    .catch(err=> {
        if(err.name === 'ValidationError') { 
            err.status = 400;
        }
        next(err);
    });
};
0

There are 0 answers