skip to Main Content

I made a get request but I have an error about _id param it can not be read

app.get(‘/users/:id’, (res, req) => {
const _id = req.params.id

    if(_id.length != 24) {
        res.status(404).send(`id length must be do not less than 24 digit`)
    } else {
        User.findById(_id).then((user) => {
            if (!user) {
                res.status(404).send(`the user id is not found `)
            }
            res.status(200).send(user)
        }).catch((e) => {
            res.status(500).send(e)
    })
    }
})

3

Answers


  1. Chosen as BEST ANSWER

    finally, I get it. it's about id in mongoose must transform it to string and then length must be equal to 12 bytes.

    app.get('/users/:id', (req,res) => {
      const _id = req.params.id
      if(_id.toString().length!= 12) {
        User.findById(_id).then((user) => 
          if(!user) {
             return res.status(404).send('unable to find user')
          }
          return res.status(200).send(user)
        }).catch((e) => {
          return res.status(500).send(e)
        })
      } else {
        res.status(400).send('bad objectID')
      }
    })
    

  2. Try:
    User.findById({_id:_id})
    Tell me if it works

    Login or Signup to reply.
  3. 
    const id = req.params.id;
    if(id.length != 24) {
            res.status(404).send(`id length sholud be 24 digit`)
        } else {
            User.findById({_id:id}).then((user) => {
                if (!user) {
                    res.status(404).send(`the user id is not found `)
                }
                res.status(200).send(user)
            }).catch((e) => {
                res.status(500).send(e)
        })
        }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search