user8628552
user8628552

Reputation: 41

Mongoose findByIdAndUpdate

I trying to edit and update a form using mongoose. The code seems fine to me, but it doesn't work. I have tried so many ways but the updated version is still the same, I uses a put route to send the form, when I output req.body.studentInfo to the console, it is correct, but the update remains the same. Please help

This is my schema

var mongoose = require("mongoose");
var uniqueValidator = require('mongoose-unique-validator');
var passportLocalMongoose = require("passport-local-mongoose");
var mongoose = require("mongoose");

var UserSchema = new mongoose.Schema({
   studentInfo: {
   first_name: String,
   middle_name: String,
   last_name: String,
   street: String,
   town: String,
   city: String,
   region: String,
   country: String,
   studentId: String,
   day: Number,
   month: String,
   year: Number,
   },                   
   username: {type: String, required:true, unique:true},
   passport: String

});
UserSchema.plugin(uniqueValidator);
UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("StudentInfo", UserSchema);

This is my App.js

app.put('/:id', function(req,res){
    StudentInfo.findByIdAndUpdate(req.params.id, {$set: req.body.studentInfo}, function(err, updated){
        console.log(req.params.id);
        console.log(req.body.studentInfo);
        if(err) {
            console.log(err);
        }
        else {
            res.redirect('/' + req.params.id);
        }
    });

});

The studentInfo is an object that contains the names of each variables in my form which I name was studentInfo[name of variable]. Please help

Upvotes: 1

Views: 6082

Answers (3)

user22958093
user22958093

Reputation: 1

you can update the body and it will only updated the changes you made and by setting new true , will make the updated data available to you immediately

StudentInfo.findByIdAndUpdate(
  req.params.id,
  { $set: body },
  { new: true }
).then((results)  {
  if (err) {
    console.log(err);
  } else {
    res.redirect( + req.params.id);
  }
});

Upvotes: 0

ImFarhad
ImFarhad

Reputation: 3229

As @Denny mentioned in his answer, mongoose will not return the updated document in the callback until you pass {new : true } option. For Details and available options check findByIdAndUpdate Docs

Upvotes: 1

Denny
Denny

Reputation: 136

It should be specified that mongoose should return the updated document - by default it returns the original (this is also the behavior of mongodb). I think that if the code gets changed to this:

StudentInfo.findByIdAndUpdate(req.params.id, {$set: req.body.studentInfo}, { new: true }, function(err, updated){
        ...
    });

you will receive the updated document in the callback.

Upvotes: 1

Related Questions