Problems with case insensitive insert & updates

So I have been working on making my database validation case insensitive for inserts as well as updates, and regarding those I’m having a couple of issues…

  1. I’m using the current code for case insensitive insert checking:

var sameName = BoxesCollection.findOne({ "name" : { $regex : new RegExp(attributes.name, "i") } });

The problem with this is let’s say I have an item named “Test Box”, then I try adding another item just named “Box”, it will detect it as a duplicate, because just “box” findOne finds the other entry.

How could I work around this issue?

  1. For my “update” functions, findOne won’t work for dupe detection because it will find itself. Is there an easy way to make it findOne without the same ID? Or would I have to do a find() and then check the results manually?

Thanks!

(Edit:

So I have had some progress on #2, but I am still having some problems.

My new code is:

var sameName = BoxesCollection.findOne({
            "name" : { $regex : new RegExp(attributes.name, "i") }, // case insensitive search
            "_id" : { $ne: attributes._id } // find not equal to current id
        }
        );

That works for finding an object with a different ID, but there is still a MAJOR problem: attribute.name is the EXISTING value, rather than the NEW value? For example:

) If I have 2 objects named MyBox, and try to update, it will find the duplicate.
) If I have 1 object named MyBox, and another named Unknown, and I try to update Unknown to name itself MyBox, it will work. Because it is searching for another object with the name MyBox - attribute.name = MyBox. It’s not the new attribute that is being passed to the insert function.

Any advice please?

You could use ^ for the beginning and $ for the end of the input. That would specify that only Box is valid, while Tom Box, Box Jerry and Tom Box Jerry are not.

1 Like

Awesome, that worked. Thank you!

Still looking advice for the updating issue! Basically I just need the Allow function to make sure not to allow the Name field to be edited to a case insensitive duplicate Name.

I am using Collection2 package, btw.