Skip to content

Commit

Permalink
Update index.md case-sensitive query (#27648)
Browse files Browse the repository at this point in the history
* Update index.md case-sensitive query

Fixed issue where adding existing genre with lowercase letters created a new genre.

* Prettier

* Update index.md - move the comment up above the code

---------

Co-authored-by: Joshua Chen <[email protected]>
Co-authored-by: Hamish Willee <[email protected]>
  • Loading branch information
3 people committed Jul 25, 2023
1 parent 24f9877 commit d6a3193
Showing 1 changed file with 7 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,18 @@ asyncHandler(async (req, res, next) => {
});
```

If the genre name data is valid then we check to see if a `Genre` with the same name already exists (as we don't want to create duplicates).
If it does, we redirect to the existing genre's detail page.
If the genre name data is valid then we perform a case-insensitive search to see if a `Genre` with the same name already exists (as we don't want to create duplicate or near duplicate records that vary only in letter case, such as: "Fantasy", "fantasy", "FaNtAsY", and so on).
To ignore letter case and accents when searching we chain the [`collation()`](https://mongoosejs.com/docs/api/query.html#Query.prototype.collation()) method, specifying the locale of 'en' and strength of 2 (for more information see the MongoDb [Collation](https://www.mongodb.com/docs/manual/reference/collation/) topic).

If a `Genre` with a matching name already exists we redirect to its detail page.
If not, we save the new `Genre` and redirect to its detail page.
Note that here we `await` on the result of the database query, following the same pattern as in other route handlers.

```js
// Check if Genre with same name already exists.
const genreExists = await Genre.findOne({ name: req.body.name }).exec();
const genreExists = await Genre.findOne({ name: req.body.name })
.collation({ locale: "en", strength: 2 })
.exec();
if (genreExists) {
// Genre exists, redirect to its detail page.
res.redirect(genreExists.url);
Expand Down

0 comments on commit d6a3193

Please sign in to comment.