在mongo中用id或用户名查找
我试图做一个用户名或_id这样的查找
exports.getUser = function (req, res){ User.find({ $or: [ {username:req.params.id}, {_id:req.params.id} ] }) .exec(function (err, collections) { res.send(collections); }); };
它在我通过_idsearch时起作用,但因用户名失败而失败,因为它无法返回有效的OjectID。 我试着做这样两个单独的查询
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); }); };
但如果用户不存在,则会挂起,因为它从不发送响应。 由于节点是asynchronous我得到Error: Can't set headers after they are sent.
如果我添加
else res.sendStatus(400);
到findById查询。 我想不出任何其他方式来解决这个问题。我尝试了MongoDB节点中的正则expression式检查objectid是否有效
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); }); };
而且我得到了同样的错误,因为它是asynchronous的。 必须有一个比这更好的方法
很可能你的第一个查询将不起作用,因为MongoDB期望_id
是一个ObjectId,而不是一个string(可能是req.params.id
):
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); }); };
- 如何检查是否有使用mongoose现有的MongoDB连接?
- 如何编写基于Node.js的cron作业来删除MongoDB集合并发出db.copyDatabase命令
- NodeJS – 获取Mongodb的属性在连接时不工作
- 什么导致SocketException(9001)在node.js app和MongoDB ReplicaSet中处理请求?
- 试图找出用于REST API的mongoose关系编码
- 一对一与mongoose的关系?
- Mongoose在启动时调用ensureIndex,但不推荐。 那么为什么这是默认的?
- mongoose填充不填充数组
- 我在我的Node.js应用程序中使用MongoSkin,并经过一段时间的不活动,失去了与数据库的连接