1

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 3

0

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

8
  • still same error Commented May 9, 2022 at 23:34
  • Can you send the whole code please
    – Emre19
    Commented May 9, 2022 at 23:35
  • ` app.get('/users/:id', (res, req) => { const id = req.params.id if(id.length != 24) { res.status(404).send(id length should 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) }) } }) ` Commented May 9, 2022 at 23:40
  • Can you show your request? Example: localhost:YOUR_PORT/users/YOUR_USER_ID
    – Emre19
    Commented May 9, 2022 at 23:42
  • localhost:3000/users/12345678 Commented May 9, 2022 at 23:43
0

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)
    })
    }
})
3
  • app.get('/users/:id', (res, req) => { const id = req.params.id if(id.length != 24) { res.status(404).send(id length should be 24 digit) } else { User.findById({ _id:id }).then((user) => { if (!user) { return res.status(404).send(the user id is not found ) } res.status(200).send(user) }).catch((e) => { res.status(500).send(e) }) } }) still same error TypeError: Cannot read properties of undefined (reading 'id') Commented May 9, 2022 at 23:33
  • I have been try this it doesn't work Commented May 10, 2022 at 0:38
  • please send us the whle code it could help Commented May 11, 2022 at 16:52
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.