【问题标题】:Find by id or username in mongo在 mongo 中按 id 或用户名查找
【发布时间】:2015-06-04 18:53:44
【问题描述】:

我正在尝试像这样通过用户名或 _id 进行查找

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 而无法输入用户名时,它可以工作。我尝试像这样进行两个单独的查询

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);
    });
};

但是如果用户不存在,这会挂起,因为它从不发送响应。由于节点是异步的,如果我添加

,我会得到 Error: Can't set headers after they are sent.
else
    res.sendStatus(400);

到 findById 查询。我想不出任何其他方法来解决这个问题。我尝试了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);
    });

};

我遇到了同样的错误,因为它是异步的。一定有比这更好的方法

【问题讨论】:

  • 为什么您的第一个选项不起作用?它应该可以工作,假设您希望它返回一个数组而不是单个用户。
  • “它无法返回有效的 ObjectID”是什么意思
  • @KevinB 它失败是因为当您提供 {_id:req.params.id} 用户名而不是 24 位十六进制代码时,mongo 会引发错误并且查询失败。所以如果 req.params.id 是 "556e06662a6efc6c2544773b" 它工作正常,但它的 "myusername" 它失败了

标签: node.js mongodb mongoose


【解决方案1】:

您的第一个查询很可能不起作用,因为 MongoDB 期望 _id 是一个 ObjectId,而不是字符串(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);
  });
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2015-03-13
    相关资源
    最近更新 更多