I’m trying to create a mongoose query that can query either by slug or id, however the problem comes in that I don’t know which one I’m going to be handling as I have this as an Express route:
app.get('/animals/dogs/:id', function (req, res, next) {
Dogs.find({$or: [{slug: id}, {_id: id}]}, function (err, docs) {
if (err) {
return next(err);
}
// ....
});
});
I’d like to have ability to search by either, however this approach above throws up an Invalid ObjectId error.
Another approach would be to nest the queries, however this feels a bit cumbersome:
app.get('/animals/dogs/:id', function (req, res, next) {
Dogs.find({slug: id}, function (err, docs) {
if (err) {
return next(err);
}
if (!docs) {
Dogs.findById(id, function (err, docs) {
// ...
});
}
// ....
});
});
Is there a any other approach I have not considered? I know I could turn my slug into the ObjectId, but I’d rather avoid this if possible.
Test if
idis a valid ObjectId and then only include that term in the query if it’s valid: