Hello I have a route that is /mysafe/idofthemodel . When the idofthemodel isnt found it throws me a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of the error i would like to have a 404 error.
Here is my route
app.get('/mysafe/:safeid',isLoggedIn,isAuthor, async(req,res)=> {
const { safeid } = req.params;
const safe=await Safe.findById(safeid).populate('author')
const password = await Password.find({safe:safeid}).populate('safe')
res.render('passwords/index', { password,safe })
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Schemas:
const PasswordsSchema = new Schema({
title: String,
url: String,
password: String,
safe: {
type: Schema.Types.ObjectId,
ref: "Safe"
},
})
const SafeSchema = new Schema({
author: {
type: Schema.Types.ObjectId,
ref: "User"
},
})
CodePudding user response:
Here I'm using EJS to render the 404 Error page, and the page file is located in views/errors/404.ejs
const { safeid } = req.params;
try {
const safe = await Safe.findOne({ _id: mongoose.Types.ObjectId(safeid) }).populate('author')
if (!safe) {
return res.status(404).render('errors/404.ejs')
}
const password = await Password.findOne({ safe: mongoose.Types.ObjectId(safeid) }).populate('safe')
return res.render('passwords/index', { password, safe })
}
catch (error) {
return res.status(500).render('errors/500')
}
middleware.js
module.exports.isAuthor = (req, res, next) => {
const { safeid } = req.params
if (!mongoose.Types.ObjectId.isValid(safeid)) {
return res.status(404).render('errors/404.ejs')
}
Safe.findById(safeid).then(safe => {
if (!safe) {
return res.status(404).render('errors/404.ejs')
}
if (!safe.author._id.equals(req.user._id)) {
req.flash('error', 'Notfound');
return res.redirect('/');
}
next();
});
}