0

I got one record with admin.name = "FooBar" And I want to do a findOne on the name but case insensitive.

In Studio3T this works fine...

db.admin.findOne(
     { name: { $regex: /^FoObAr/i } }
)

But in nodeJS I cant seem to get a variable containing the regexp into the find statement...

Let ID = "FoObAr"
return resolve( adminModel.findOne( { "name" : { $regex: "/^" + ID + "$/i"} } ) );

This one results in... (which gives 0 results)

Mongoose: admin.findOne({ name: { '$regex': '/^FoObAr$/i' } }, { projection: {} })

I also tried

Let ID = "FoObAr"
return resolve( adminModel.findOne( { "name" : { $regex: /^ ID $/i } ) );

This one results in... (which gives 0 results)

Mongoose: admin.findOne({ name: { { $regex: /^ ID $/i } }, { projection: {} })

Any ideas?

2 Answers 2

1

Please use RegExp function

admin.find({name:new RegExp(['^',ID, '$'].join(''), 'i')}).projection({})
Sign up to request clarification or add additional context in comments.

1 Comment

Executed it perfectly... collection.js:204 Mongoose: admin.findOne({ name: /^FoObAr$/i }, { projection: {} })
1

You should pass RegExp object, not string.

adminModel.findOne({ "name" : { $regex: new RegExp(/^FoObAr/, 'i') } })

With variable ID it will look like

adminModel.findOne({ "name" : { $regex: new RegExp(`^${ID}$`, 'i') } })

1 Comment

Dosnt show me how to put the ID variable inside, so I once again end up like this.. { "name" : { $regex: new RegExp("/^" + ID + "/", 'i') } which does not work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.