Home > Enterprise >  TypeError: Cannot read properties of undefined (reading 'id') mongoose db
TypeError: Cannot read properties of undefined (reading 'id') mongoose db

Time:05-10

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

CodePudding user response:

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

CodePudding user response:


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

CodePudding user response:

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

})

  • Related