From d6a319353378bba7bca027864c24bd573a643987 Mon Sep 17 00:00:00 2001 From: NeoxAA <58242302+NeoxAA@users.noreply.github.com> Date: Tue, 25 Jul 2023 03:16:31 -0400 Subject: [PATCH] Update index.md case-sensitive query (#27648) * 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 Co-authored-by: Hamish Willee --- .../express_nodejs/forms/create_genre_form/index.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/files/en-us/learn/server-side/express_nodejs/forms/create_genre_form/index.md b/files/en-us/learn/server-side/express_nodejs/forms/create_genre_form/index.md index ab920c760c2db2e..2e92113039107b0 100644 --- a/files/en-us/learn/server-side/express_nodejs/forms/create_genre_form/index.md +++ b/files/en-us/learn/server-side/express_nodejs/forms/create_genre_form/index.md @@ -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);