Robert
Robert

Reputation: 1266

Mongoose - findByIdAndUpdate - doesn't 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?

Upvotes: 10

Views: 43600

Answers (3)

Barno
Barno

Reputation: 3331

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},{new:true}, function(err, result){
        if(err){
            console.log(err);
        }
        console.log("RESULT: " + result);
        res.send('Done')
    });
};

Upvotes: 16

Neelavar
Neelavar

Reputation: 368

Further, the req.body would have key value as Text and realized as String object, inside the code. Thus, it is useful to parse the string into JSON using JSON.parse(req.body.user) - while the user is the key and { first_name: 'Michal', last_name: 'Test' } is the value.

console.log(req.body);
var update = JSON.parse(req.body.user);
var id = req.params.user_id;
User.findByIdAndUpdate(id, update, function(err, result){
    if(err){
        console.log(err);
    }
    console.log("RESULT: " + result);
    res.send('Done')
});

Note: the update value is sent to Mongo DB as

{$set: { first_name : 'Michal`, last_name: 'Test' } 

Further reference: Mongoose JS documentation - findByIdAndUpdate

Upvotes: 0

Robert
Robert

Reputation: 1266

I found the mistake. Note that I'm calling

req.body.user_id

where should be

req.params.user_id

  • url is (PUT) http://127.0.0.1:3000/api/users/54724d0fccf520000073b9e3

Upvotes: 1

Related Questions