Mongoose - findByIdAndUpdate - not working with req.body

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

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

      

The controller will put the function 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')
}

      

Console output:

Listening on port 3000... { first_name: 'Michal', last_name: 'Test' } 
PUT /api/users/54724d0fccf520000073b9e3 200 58.280 ms - 4

      

Printable parameters are provided as form data (key value). Doesn't seem to work, at least for me some idea, what's wrong here?

+3


source to share


3 answers


Instead, you should use req.params.user_id

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

      

+11


source


I found a bug. Please note that I am calling

req.body.user_id

where should be



req.params.user_id

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

+1


source


It req.body

will also be key in the form of text and implemented as an object String

within the code. Thus, it is useful to parse a string into JSON using JSON.parse(req.body.user)

- while 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 link: Mongoose JS Documentation - findByIdAndUpdate

0


source







All Articles