【问题标题】:mongoose search using regex on findbyid在 findbyid 上使用正则表达式进行猫鼬搜索
【发布时间】:2020-08-05 18:40:05
【问题描述】:

我需要通过他的mongodb集合的_id找到一个用户,

需要使用用户 ID 中的前 5 个字符进行搜索

5e9cca 的示例我可以找到集合 ID 5e9cca24beabb96a4caedc35

    var id = req.body.id

    User.findById({ _id : { $regex: '^id', $options: 'i' } },  
     (err, user)  => {
        if (err) {
             console.log(err);
           res.status(400)
       }

使用这段代码我得到了这个错误:

MongooseError [CastError]: Cast to ObjectId failed for value "{ _id: { '$regex': '^id', '$options': 'i' } }" at path "_id" for model "User"

PS : 使用洞 id 的搜索正在工作

【问题讨论】:

    标签: node.js regex mongodb mongoose mongodb-query


    【解决方案1】:

    Mongoose 的.findById() 将接收一个字符串,并在内部将字符串转换为ObjectId()。所以.findById() 是 MongoDB 的原生函数 .findOne() 的一种包装器,它所能接受的只是一个字符串。此外,您不能对_id 字段进行正则表达式搜索,因为它不是string 类型。如果您需要这样做,请尝试以下操作:

    在 MongoDB 版本 >4.0 上:

    db.collection.aggregate([
      /** Create a field of type 'string' from `_id`*/
      { $addFields: { convertedId: { $toString: "$_id" } } },
      /** Regex search against it */
      {
        $match: {
          convertedId: {
            $regex: "^1a934e",
            $options: "i"
          }
        }
      },
      /** Remove additionally added field */
      { $project: { convertedId: 0 } }
    ])
    

    测试: mongoplayground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 2017-12-07
      • 2021-08-02
      • 1970-01-01
      • 2014-10-21
      • 2020-10-04
      • 2019-02-18
      相关资源
      最近更新 更多