在mongo中按ID或用户名查找 [英] Find by id or username in mongo
问题描述
我正在尝试通过用户名或_id进行查找
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);
});
};
当我通过_id搜索但无法输入用户名时,它可以工作,因为它无法返回有效的OjectID.我试过像这样两个独立的查询
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);
到findById查询.我想不出任何其他方法来解决这个问题.我在 MongoDB节点检查objectid是否有效
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
推荐答案
您的第一个查询很可能无法正常工作,因为MongoDB期望_id
是ObjectId,而不是字符串(req.params.id
可能是字符串) :
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);
});
};
这篇关于在mongo中按ID或用户名查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!