Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Query for starts with

Tags:

I want to basically do a username search.

User.find({ username: "Mich"})

I'd like a query like the above that'll return all users who's username starts with "Mich". Michael, Michaela, MichJagger, etc.

like image 884
opticon Avatar asked Apr 22 '15 22:04

opticon


People also ask

How do you get all the values that contains part of a string using mongoose find?

To get all the values that contains part of a string using Mongoose find , we can use the $regex operator. Books. find({ "authors": { "$regex": "Alex", "$options": "i" } }, (err, docs) => {} );

What is $GTE in mongoose?

$gte selects the documents where the value of the field is greater than or equal to (i.e. >= ) a specified value (e.g. value .)

What does find () return in mongoose?

find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

What is skip and limit in mongoose?

The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.


1 Answers

You can search with regex, this should work in Node

User.find({ username: /^Mich/})

Note that Mongo supports regex objects, which means you can do

var regexp = new RegExp("^"+ req.params.username);
User.find({ username: regexp});

or Mongos own regex constructor

User.find({ username: {$regex : "^" + req.params.username}});
like image 98
adeneo Avatar answered Sep 27 '22 21:09

adeneo