简体   繁体   中英

How to check for a valid Object Id in mongoose?

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) } })

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