Damien
Damien

Reputation: 1647

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?

Upvotes: 0

Views: 82

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Test whether req.params.userId is a valid ObjectId and then assemble your query based on that:

let query = {};
if (req.params.userId.match(/^[0-9a-fA-F]{24}$/)) {
    query._id = req.params.userId;
}
else {
    query.username = req.params.userId;
}
User.find(query, ...);

Upvotes: 1

Related Questions