简体   繁体   English

如何在猫鼬中检查有效的对象 ID?

[英]How to check for a valid Object Id in mongoose?

I have a route that returns a particular story from an object Id.我有一条从对象 ID 返回特定故事的路线。 When i try testing it, it gives me some errors.当我尝试测试它时,它给了我一些错误。 The code inside if block is not executing somehow. if 块中的代码没有以某种方式执行。

 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如果 id 无效,我不想执行查询,比如/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.首先,我们我们方法isValidmongoose.Types.ObjectId则作为第二检查,我们创建一个实际的对象ID的比较,它作为一个字符串。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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