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.
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) => {} );
$gte selects the documents where the value of the field is greater than or equal to (i.e. >= ) a specified value (e.g. value .)
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.
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.
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}});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With