I have the following mongodb code that works in returning a group name (regardless of case)
code = "group1";
let group: any = await this.groupModel.findOne({
name: { $regex: code, $options: "i" },
});
However, some of the group names in my db have spaces e.g - "group 1", and my code variable I am passing in, will always have no spaces.
Is there a way to ignore any spaces in a mongodb find, so if my code variable is "group1", it will still return group names called 'group 1' or 'group1'?
CodePudding user response:
You can use ?
to make the space \\s
character optional and find all the documents that either group1
or group 1
like below-
code = "group\\s?1";
let group: any = await this.groupModel.findOne({
name: { $regex: code, $options: "i" },
});
In MongoDB I think one way to ignore space is possible but that is on patterns
not on values, See: https://www.mongodb.com/docs/manual/reference/operator/query/regex/#ignore-white-spaces-in-pattern