【问题标题】:How do I use a variable with the mongo 'like' operation when comparing a number?比较数字时如何使用带有 mongo 'like' 操作的变量?
【发布时间】:2021-02-05 10:55:04
【问题描述】:

我尝试了相同的方法,但没有使用单独的变量 search_num 并使用搜索变量本身,但同样的问题仍然存在,这就是我进行类型转换的原因。用邮递员测试过 这是我的架构 -

const lender_details = mongoose.Schema({
        lender_id : Number,
        investment_id: Number,
        name: String,
        email: String,
        mobile_no : Number,
        reg_date: Number,
        live_status: String,
        lender_details: String,
    })

我想做的只是有一个通用的搜索框,通过投资 ID、电话和电子邮件进行搜索。

router.post('/', async (req,res,next) => {
    search = req.body.search;

    search_num = Number(search);
    console.log({$regex : search_num});
   await a.find({
     "investment_id" :($regex : search_num),
       "email" : { $regex : search } }
    ,{ _id : false })

/m/ 概念在使用变量时不起作用,因此我使用了正则表达式,但在尝试了几乎所有方法后,当我尝试搜索数字投资 ID 时,此错误仍然存​​在 - 模型“lender_details”的路径“investment_id”中值“/1/”的数字转换失败 任何和所有的帮助表示赞赏!

【问题讨论】:

  • '/1/' 不是数字,你为什么要把它转换成Number(search)...?
  • 在 mongodb 中搜索不需要提供正则表达式。只需使用:` await a.find({ "investment_id" :search_num, "email" : search } ,{ _id : false })`
  • 嗨,原因是我不想做精确搜索,想在 SQL 中做类似于 LIKE %m% 的事情,希望这能回答你的问题
  • {$regex: new RegExp(req.body.search)}…?
  • @deceze 同样的错误仍然存​​在:)

标签: javascript node.js api mongodb-query


【解决方案1】:

Iirc 你应该先用一些搜索管道把它翻译成字符串,然后你可以用正则表达式搜索它; 让我举一些例子;

a.find({
"$expr": {
    "$regexMatch": {
       "input": {"$toString": "$investment_id"}, 
       "regex": search_num_regexp 
    }
})

iirc 您可以使用 where 运算符,但它可能会降低性能查询,我不确定它是否能正常工作。但它会像下面这样

a.find({
  $where: `${search_num_regexp}.test(this.example)`
})

【讨论】:

    猜你喜欢
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    相关资源
    最近更新 更多