Robert Robert - 6 months ago 32
Node.js Question

Mongoose - findByIdAndUpdate - doest not work with req.body

I have a problem with update documents in mongodb over mongoose.

My model bellow:

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 bellow:

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')
}


Output on console:

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 at least for me any idea what is wrong here?

Answer

You have to use req.params.user_id instead req.body.user_id

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')
    });
};