I have the following problem to solve: I have multiple users in a database (mongoDB). Pass the following, in a specific url, for example: "my-page/users/here-goes-the-name-of-the-user". When displaying the username in the url, I convert it to lowercase and replace the spaces with hyphens: Husdady Mena ===> /husdady-mena.
In the database, the user names are as shown before converting the name to lowercase, eg: Husdady Mena, Donald Trump, Will Smith, etc.
I need to somehow filter a user, which is in the url as /husdady-mena with the database user: Husdady Mena, in order to obtain his information, how could that filter be done in mongoose?
A clear example with js:
const users = [{ name: 'Husdady Mena' }, {name:'Donald Trump'}, {name:'Will Smith'}, {name:'Dubá Solis'}]
const username = "dubá-solis"
const url = `my-page.com/users/${username}`
const userToFilter = url.substring(url.lastIndexOf("/") 1)
const userFound = users.find(({ name }) => {
const usernameToLowerCase = name.toLowerCase().replace(/\s/gim, "-")
return userToFilter === usernameToLowerCase
})
console.log(userFound)
If the example is not clear to you: I make a request from the frontend to the backend to obtain a specific user, I need to obtain the user by name, it is not necessary to obtain it by id. In the url something like: my-page/users/dubá-solis is painted, I get the name of the user, which is: dubá-solis. in the backend is something like:
// Librarys
const { Router } = require('express')
const router = Router()
// Models
const User = require('@models/users/User')
router.get(
'/users/:username',
function(req, res) {
try {
// req.params.username === "dubá-solis"
const userFound = await User.findOne({ name: req.params.username })
// In database, the username is Dubá Solis, that's why it returns me null
return res.status(200).json(userFound)
} catch(err) {
console.log('[UserFound.err]', err)
}
}
)
module.exports = router
CodePudding user response:
Why not just convert the username and pass that to the query function? Something like:
const convertUsername = username => {
const nameParts = username.split('-');
return nameParts.map(n => n.slice(0, 1).toUpperCase() n.slice(1))
.join(' ');
};
console.log(convertUsername('dubá-Solis'));
console.log(convertUsername('joan-of-arc'));
Then, just do User.findOne({ name: convertUsername(req.params.username) })