How to make changes on a usurious registered with the PUT method?

Asked

Viewed 24 times

0

Hello I am learning Java, now in the back end I have set up a user registration API Email,Name,Age,Phone. I used the POST method to insert the new user in the array and GET to show the users, so far so quiet. Now I wanted to make changes to a registered user with PUT, to travado kk

  • Your question seems to have some problems and your experience here in Stack Overflow may not be the best because of it. We want you to do well here and get what you want, but for that we need you to do your part. Here are some guidelines that will help you: Stack Overflow Survival Guide in English (short version). If the solution is very simple it is still possible for someone to do so in the comments.

1 answer

0


Here is an example of update code using mongodb. But this same logic can be used for relational databases.

usuario.routejs.

const router = require('express').Router();
const userController = require('../controllers/user.controller');
//...
router.put('/users/:id', userController.updateUserbyId);
//...
module.exports = router;

usuario.controller.js

exports.updateUserbyId = (req, res) => {
    const options = { returnOriginal: false };
    db.get().collection('user').findOneAndUpdate({_id: ObjectId(req.params.id)}, {$set: {"name": req.body.name }}, options).then((result) => {
        if (result.value === null) {
            return res.status(404).json({ errors: [{location: "users", msg: "Not found", param: req.params.id}]})
        }
        res.status(200).json(result.value);
    }).catch((err) => {
        res.status(500).json({errors: [{location: "users", msg: err, param: req.params.id}]})
    })
}

I also recommend validating the entry before entering the database.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.