0

I am using MongoDB nodeJS driver to MongoDB database.

Trying to get single result from the database using collection.findOne() with a query object.

When it is executed, the script gives me null response. However if the same is executed from the mongo shell, it gives me a response with one document.

Below is the code sample which is making the query to Database.

construct(venue) {
  console.log(venue) /* prints -> I love to sit in A\/C */
  let promise = new Promise((resolve, reject)=>{
    myCollection.findOne({
      "Venue": venue
    }) 
    .then( r => {
      if(r == null) {
        throw new Error("Venue name dose not exits in the response");
      } else {
        resolve(r.VenueCode)
      }
    })
  }
  return promise;
}

venue is a variable which I got after parsing the query parameter from the request URL.

let venue = req.query.venue;

This seems happens only when there is a '\' character in the venue variable.

For Ex:

    I love to sit in A\/C (dose not work! null result)
    I love AC ( works fine)

The same string(with backslash) works inside the mongo shell.

db.myCollection.find({"Venue":"I love to sit in A\/C"}).pretty()
{
    "_id" : ObjectId("5babsdf92f2c5082d5f478aebfa"),
    "VenueCode" : "ABCD",
    "Venue" : "I love to sit in A/C ",
    "list" : "9999"
}

Update:

Thanks @TimaGegewepe. Removing the backslah from venue variable did solved my problem.

However still one thing is unclear - when I Insert the data to the modgoDB through another script, It had back slash in the insert document. Inside the mongo shell when I execute the find() with query containing backslash, without back slash both elides the result, But through my script, I have to remove the backslashes inside the query object.

vikas kv
  • 386
  • 2
  • 15
  • 1
    Did you try to escape the backslash? – Void Spirit Sep 26 '18 at 15:20
  • There's no need to construct your own Promise. How are you calling your `construct`? –  Sep 26 '18 at 15:21
  • I copy-pasted your example document and tried to insert it into a collection. The resulting document has `"Venue": "I love to sit in A/C "` (no backslash). I believe this is a string sanitation issue, and not really a MongoDB/express issue. – kevinadi Sep 27 '18 at 00:24
  • This makes no sense ... the db record coming back cannot be with `I love to sit in A\/C ` if you query with `find({"Venue":"I love to sit in A\/C"})`. It should be coming back with `I love to sit in A/C `. Just tested in locally. – Akrion Sep 27 '18 at 02:00

1 Answers1

0

Have you tried like a this ?

let v='I love to sit in A\/C';

db.myCollection.findOne({"Venue": /.v./})

How to query MongoDB with "like"?

Ujjual
  • 958
  • 2
  • 10
  • 36