Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

While updating the documents in mongodb over mongoose, I am some error. Below is my model:

var mongoose = require('mongoose');

var bcrypt = require('bcrypt-nodejs');

var UserSchema = new mongoose.Schema({

    first_name:{

        type: String

    },

    last_name:{

        type: String

    },

    email:{

        type: String,

        unique: true,

        required: true

    },

    password:{

        type: String,

        required: true

    },

    is_active:{

        type: Boolean,

        default: true

    },

    last_login:{

        type: Date

    }

});

module.exports = mongoose.model('User', UserSchema);

Controller put function is shown below:

exports.updateUser = function (req, res) {

    console.log(req.body);

    User.findByIdAndUpdate(req.body.user_id, {$set:req.body}, function(err, result){

        if(err){

            console.log(err);

        }

        console.log("RESULT: " + result);

    });

    res.send('Done')

}

The output on the console is as follows:

Listening on port 3000... { first_name: 'Michal', last_name: 'Test' } 

PUT /api/users/54724d0fccf520000073b9e3 200 58.280 ms - 4

The printed params are provided as form-data (key-value). Looks that is not working, can you guide me what is wrong here?

1 Answer

0 votes
by (107k points)

You have done one mistake, what you have done is you have used req.body.user_id instead of using req.params.user_id. Refer to the following code:

exports.updateUser = function (req, res) {   

    console.log(req.body);

    User.findByIdAndUpdate(req.params.user_id,{$set:req.body}, function(err, result){

        if(err){

            console.log(err);

        }

        console.log("RESULT: " + result);

        res.send('Done')

    });

};

Req.params is only for the route parameters and the only parameter that the route contains is the _id like say for instance you have the route as /user/:username, then the “username” feature is available as req.params.name. This object is set by defaults to an empty dictionary whereas the req.body contains the key-value pairs for the data that is submitted to the request body and by default it is undefined.   

If you want to learn more about MongoDB then go through this MongoDB course for more insights.

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...