Monday, 15 May 2017

Find by two separate data types with Mongoose

I want to be able to find a user in my MongoDB (using Mongoose) by either a username or ID.

Using: User.find({ $or: [ { _id: req.params.userId }, { username: req.params.userId } ]}, ... throws an error when I pass it a string:

Cast to ObjectId failed for value \"username\" at path \"_id\" for model \"User\""

I understand why I'm getting the error, but is there an easy way around it?



via Damien

No comments:

Post a Comment