app.post("profile/:id", (req, res) => { const id = req.params.id User.findById(id).then((user) => { if (!user) { res.status(404).send('Resource not found') } else { const keys = Object.keys(req.body) keys.forEach(key => { if (key === "username") { const foundUser = User.findOne({ "username": req.body.username }) if (foundUser === null) user.username = req.body.username } }) user.save() } }) .catch((error) => { log(error) res.status(500).send('Internal Server Error') // server error }) });
basically a user has properties {_id: objectid, username: string, password: string, .. etc}
I send this route a json like below to change its username
{"username": "Admin123"}
Assume Admin123 doesn’t exist then const foundUser
would not be null because there is no user in the user collection with username Admin123. However const foundUser is never null? I’m not sure what I am doing wrong
Advertisement
Answer
Hay there, How about a smaller solution I’m giving you that to just make your code better
What’s wrong with your code ??
- You are querying the same user twice!
- You are in the hill of callback functions
- Looping the user when you know that it does have a ‘username’
- SHOULD NOT USE SAVE METHOD direct.
What you should do first you should check if there is any existing, user with the same username ! you should return duplicate or not allowed or already exist
And you should use the querying feature in mongoose or any other DB cuz it’s faster
read my code below and I’ll help you if you don’t get it.
feel free to comment down or reach me on fb.com/mustafa.ali2
// I'm using here async await which is much cleaner and easy to read 😄 app.post('profile/:id', async (req, res) => { // Try catch for any error other error 😇 try { // Destructuring the id form req.params (new way to do things !) const { id } = req.params // Querying the DB (MongoDB) and updating when we fond the user that match the given _id 😉 const user = await User.findOneAndUpdate( { _id: new mongoose.Types.ObjectId(id), username: null }, { $set: { username: req.body.username } } ) // if user not found return error 🙂 if (!user) return res.status(404).send('Resource not found'); // if user found return success 🙂 res.status(200).send('Updated successfully'); } catch (err) { log(err); res.status(500).send('Internal Server Error'); } })