I have a route that returns a particular story from an object Id. When i try testing it, it gives me some errors. The code inside if block is not executing somehow.
router.get("/:id",async (req,res) => {
try{
if (!isValidObjectId(req.params.userId)) {
res.status(401).json({
message: "Invalid object id",
success: false
})
throw new Error("Invalid object id")
}
let story = await Story.findById(req.params.id)
.populate('user')
.lean()
if (!story) {
return res.status(404).json({
message: "Story not found",
success: false
})
}
const text = convert(story.body, {
wordwrap: null
});
res.render('stories/show',{
story,
title: `${story.title} Storybooks`,
desc: `${text}`
})
}
catch(err) {
console.error(err)
}
})
I don't want to execute the query if the id is not valid say /stories/blabla
How can i do that?
Your response is appreciated.
For those of you struggling with the problem here is a time saver:
First we us the method isValid on mongoose.Types.ObjectId then as a 2nd check we create an actual object id an compare it as a string.
Here's how you would import and use it:
const mongoose = require('mongoose');
const {Types: {ObjectId}} = mongoose;
const validateObjectId = (id) => ObjectId.isValid(id) && (new ObjectId(id)).toString() === id; //true or false
As to answering my own question:
const mongoose = require('mongoose');
const {Types: {ObjectId}} = mongoose;
const validateObjectId = (id) => ObjectId.isValid(id) && (new
ObjectId(id)).toString() === id; //true or false
// @desc Show a single story
// @route GET /stories/:id
router.get("/:id",async (req,res) => {
try{
if (!validateObjectId(req.params.id)) {
throw Error("Invalid object Id")
}
let story = await Story.findById(req.params.id)
.populate('user')
.lean()
if (!story) {
return res.status(404).json({
message: "Story not found",
success: false
})
}
const text = convert(story.body, {
wordwrap: null
});
res.render('stories/show',{
story,
title: `${story.title} Storybooks`,
desc: `${text}`
})
}
catch(err) {
console.error(err)
}
})
EDIT:
I used req.params.userId instead of req.params.id so the above method is totally fine.
But just learnt a new way of doing it.