Mongoose - findByIdAndUpdate - doesn't work with req.body

后端 未结 3 1989
孤街浪徒
孤街浪徒 2021-02-14 17:57

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

My model bellow:

var mongoose = require(\'mongoose\');
var bcrypt = require(\'bcrypt-nod         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-14 18:33

    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

提交回复
热议问题