butthash3030
butthash3030

Reputation: 173

Why does my Array.prototype.find() return undefined?

I have a route handler in which I am attempting to find a user's collection of club objects, then find the specific club object using Array.prototype.find(). I have no idea why it is always returning undefined. Can anyone see what I am doing wrong?

router.get('/club', async (req,res) => {
    try {

        console.log(req.query.club); 
        // 6008d7537ea5c22b61dc616b
        
        const { clubs } = await User.findOne({ spotifyId: req.query.id }).populate('clubs').select('clubs');
        
        console.log(clubs); 
        // [{"_id":"6008d7537ea5c22b61dc616b","name":"asfasfs","description":"sdfasfa","privacy":"private","frequency":"bi-weekly","__v":0},{"_id":"6008ec8026900630c24fd533","name":"asfasfdsasf","description":"asdfasfdsf","privacy":"private","frequency":"monthly","__v":0}]
        
        let club = clubs.find(currentClub => (
           currentClub._id === req.query.club
        ));

        console.log(club)
        // undefined
        
        res.send(club)
    }
    catch {
        return res.status(400).send('No club found with given id')
    }
})

Upvotes: 0

Views: 345

Answers (1)

Trung Ngoc
Trung Ngoc

Reputation: 29

_id is an object

Change your code like this

String(currentClub._id) === req.query.club

or

currentClub._id.toString() === req.query.club

Upvotes: 1

Related Questions