MongoDB: How to avoid name doubles in collection

Viewed 41

Since I couldn't find anything in search, I would try my luck with asking a question here:

I am trying to create unique documents in a "customers" collection, and in order to make sure they are unique, I search through the (unique!) name fields in the collection to check if the customer has already been created. Now I am trying to rule out case-sensitive doubles as well as white space doubles. (Example customer: "SpaceX" already exists, so I shouldn't be able to create "Spacex" or "SpaceX " or "Space X", just to make sure the document for the customer is unique).

So what I am trying to do is go through the indexed name fields with $regex, and if it finds something, return an error.

I have found that customer.find({name: {$regex: new RegEx(name), $options: 'ix' }) does not work in this scenario, but according to documentation, that should filter out white space trimmed and case-insensitive documents for that name.... It's driving me crazy. Anyone knows how to approach this?

Here is my current code that places the check:

  let existingCustomer
  try {
    console.log(new RegExp(name), typeof name)
    existingCustomer = await Customer.find(
      {
        name: { $regex: new RegExp(name), $options: 'ix' },
      },
      '-products -tam -responsiblePerson -info -created -updated'
    )
    console.log(existingCustomer)
  } catch (err) {}

  if (existingCustomer.length > 0) {
    console.log(existingCustomer[0])
    const error = new HttpError(
      'Customer name already exists, please use a different name.',
      500
    )
    return next(error)
  }
1 Answers

You can do this:

Customer.find({
        name: { $regex: new RegExp("^" +name.replace(/\s/g, ''), "i") }
      })

but since mongoose 3.4, it is recommended to use case sensitive index: documentation here

so you can simply do:

Customer.find({
         name: name.replace(/\s/g, '')
        })
       .collation( { locale: 'en', strength: 2 } )
Related