Reputation: 143
I'm trying to do a find by username or _id like this
exports.getUser = function (req, res){
User.find({ $or: [ {username:req.params.id}, {_id:req.params.id} ] })
.exec(function (err, collections) {
res.send(collections);
});
};
It works when I search by _id but fails for username because it fails to return a valid OjectID. I tried doing two separate queries like this
exports.getUser = function (req, res){
User.findOne({username:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
};
but this hangs if the user doesn't exist because it never sends a response. Since node is async I get Error: Can't set headers after they are sent.
if I add
else
res.sendStatus(400);
to the findById query. I can't think of any other way to solve this.I tried the regex in MongoDB Node check if objectid is valid
exports.getUser = function (req, res){
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if(checkForHexRegExp.test(req.params.id)){
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
}
User.findOne({username:req.params.id}).exec(function (err, user) {
res.send(user);
});
};
And I'm getting the same error because it's async. There has to be a better way than this
Upvotes: 2
Views: 6279
Reputation: 203304
Most likely your first query won't work because MongoDB is expecting that _id
is an ObjectId, and not a string (which req.params.id
probably is):
var ObjectId = require('mongoose').Types.ObjectId;
exports.getUser = function (req, res) {
var id = req.params.id;
var $or = [ { username : id } ];
// Does it look like an ObjectId? If so, convert it to one and
// add it to the list of OR operands.
if (ObjectId.isValid(id)) {
$or.push({ _id : ObjectId(id) });
}
User.find({ $or : $or }).exec(function (err, collections) {
// TODO: check for errors
res.send(collections);
});
};
Upvotes: 6