Home > OS >  Update record based on username given in Request body
Update record based on username given in Request body

Time:10-05

I need to update value in Group db Group_name to the value send in Json payload.

Db schema

const mongoose = require('mongoose');

const UserSchema = new mongoose.Schema({
    username: String,
    Group_name: {
        type: String,
        default: '',
    }
});

mongoose.model('User', UserSchema);

And API request

router.put('/join', async(req, res) => {
    try {
        const data = await User.updateOne(req.params.username, {
            Group_name: req.body.Group_name
        });
        console.log(data)

        res.send({ msg: "Group Updated!!!" })

    } catch (err) {
        console.error(err.message);
        res.sendStatus(400).send('Server Error');
    }
});

currently its updating only first record which is incorrect , my requirement is to check for all records based on username given and according to username given in request parameters ,i will update value of Group_name to the value sent in request body. can anyone help me ?

CodePudding user response:

Modify query condition.

const data = await User.updateOne(
    { username: req.params.username }, 
    { $set: { Group_name: req.body.Group_name } }
);

CodePudding user response:

First of all, understand the difference between req.body & req.params

req.body means hidden parameters sent in request body like in post or put requests.

req.params means defined paramters in URL. For this, you must have it defined in your route like below

router.put('/join/:username', async (req, res) => {
                // ^^^^^^^^ here it is defined, now you can access it like
    const username = req.params.username;
//or
    const {username} = req.params;   // destructuring
}

there is one more thing and that is

req.query means undefined paramters attached to URL with ?/&

If you want to give username without pre defining like /join?username=john then use req.query

router.put('/join', async (req, res) => {                  
    const {username} = req.query;
}

Then you should use updateMany() function instead of updateOne()

try {
    const {username} = req.params;
    const {Group_name} = req.body;
    const data = await User.updateMany(
        {username},     // find as many users where username matches
        {Group_name}    // update group name from body
    );

    console.log(data);

The consoled data would be like { n: 2, nModified: 2, ...} because the update queries don't return updated documents but status of the query. If you want to get updated record set, you have to query again with find().

// after update
const updatedRecord = await User.find({ username });
console.log(updatedRecord);

::POSTMAN::

Postman has two types of parameters

  1. Params
  2. Body

postman request parameter types

  • If you add in Params it will be added in URL /[email protected]&Group_name=GroupB and you have to access it in code with req.query.username or req.query.Group_name
  • If you add in Body it will be hidden and can be accessed with req.body.Group_name etc

Hope it helps!

  • Related