Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

javascript - How do I use a variable with the mongo 'like' operation when comparing a number?

I have tried the same without using a separate variable search_num and use the search variable itself but the same issue persists, thats the reason I typecasted. Was tested with postman this is my schema -

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

All I'm trying to do is have a common search box, that searches through investment ID,phone and email.

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

The /m/ concept does not work when using a variable and so I have used regex, but after trying almost everything this error persists when I'm trying to search the investment ID which is a number - Cast to Number failed for value "/1/" at path "investment_id" for model "lender_details" Any and all help appreciated !

question from:https://stackoverflow.com/questions/66061977/how-do-i-use-a-variable-with-the-mongo-like-operation-when-comparing-a-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Iirc you should translate it firstly to string with using some search pipe then you can search it with regex; Let me show some of example;

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

or

iirc you can use where operator but it will maybe decrease the performance query and i am not sure if it will work correctly. but it would something like below

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...