Hamdi Chebbi
Hamdi Chebbi

Reputation: 1

Update a document with FindByIdAndUpdate

I have an issue with Mongoose where findByIdAndUpdate is not returning the correct model in the callback.

I want to update the TIMELINE.Description attribute from a user document:

var refereeSchema = mongoose.Schema({
    first_name: String,
    last_name: String,
    email: String,
    phone: Number,
    age: Number,
    role: String,

    note: Number,
    favorite_teams: String,
    hometown: String,
    picture: String,
    timeline: 
        {
            id_Game1: String,
            date_game: Date,
            description: String
        }

})  ; 

// new timeline
router.put('/:id', function(req,res,next){
      models.users.findByIdAndUpdate(req.params.id,{$set: {description : req.body.description}}, {new:true} , function(err,user){
       if(err){
           res.json({error :err}) ; 
       } else{
           res.send(user) ; 
       }
    });
});

Upvotes: 0

Views: 5257

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311845

You're missing the timeline portion of the subdocument key to update. It should be:

router.put('/:id', function(req,res,next){
    models.users.findByIdAndUpdate(
        req.params.id,
        {$set: {'timeline.description': req.body.description}}, 
        {new: true},
        function(err,user){
            if(err){
                res.json({error :err}) ; 
            } else{
                res.send(user) ; 
            }
        });
});

Upvotes: 1

Related Questions