Mongoose schema: Validating unique field, case insensitive
What about using:
{ type: String, lowercase: true, trim: true }
to achieve your purpose?
A collation with strength: 2
on the index solves this issue.
index: { unique: true, collation: { locale: 'en', strength: 2 }}
Place this in your Schema creation code as follows:
var userSchema = new Schema({ ... username: { type: String, required: true, index: { unique: true, collation: { locale: 'en', strength: 2 } }});
Note: make sure the index on the model gets updated - you might need to do this manually.
... with mongoose on NodeJS that query:
const countryName = req.params.country;{ 'country': new RegExp(`^${countryName}$`, 'i') };
or
const countryName = req.params.country;{ 'country': { $regex: new RegExp(`^${countryName}$`), $options: 'i' } };// ^australia$
or
const countryName = req.params.country;{ 'country': { $regex: new RegExp(`^${countryName}$`, 'i') } };// ^turkey$
A full code example in Javascript, NodeJS with Mongoose ORM on MongoDB
// get all customers that given country nameapp.get('/customers/country/:countryName', (req, res) => { //res.send(`Got a GET request at /customer/country/${req.params.countryName}`); const countryName = req.params.countryName; // using Regular Expression (case intensitive and equal): ^australia$ // const query = { 'country': new RegExp(`^${countryName}$`, 'i') }; // const query = { 'country': { $regex: new RegExp(`^${countryName}$`, 'i') } }; const query = { 'country': { $regex: new RegExp(`^${countryName}$`), $options: 'i' } }; Customer.find(query).sort({ name: 'asc' }) .then(customers => { res.json(customers); }) .catch(error => { // error.. res.send(error.message); });});