Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js MongoDB .findOne returns best match when querying a String

Node.js MongoDB .findOne returns best match when querying a String

Problem

If I create a document in MongoDB using the create method.

Ua.create({myStringField: 'myStringData'}, function(err, myUa){
  callback(err,myUa);
});

Later I then want to search for a new string in the database and use this method.

Ua.findOne({myStringField: 'myStringDataNEW'}, function(err, myUa){
  callback(err,myUa);
});

Notice that I set the original myStringField with data 'myStringData' and am now searching for 'myStringDataNEW'. The findOne() method returns the document containing 'myStringData' as the result of this query.

How do I query only for exact matches to strings in MongoDB?

Many thanks for your help.

Problem courtesy of: David

Solution

I'm pretty certain you are getting confused. Your findOne call will do an exact, case-sensitive match. To do partial matches or case-insensitive you need to use a RegExp instance not a basic string. My suggestion is to make a simple test case separate from your app, and my suspicion is the DB is not behaving the way you think it is.

Solution courtesy of: Peter Lyons

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js MongoDB .findOne returns best match when querying a String

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×