1

I want to create an experience array in User model with new data, and the problem is that I don't get saved data in exec function so I can push new data in array on frontend. This is what I got so far.

router.post('/:username/experience', function(req, res) {
const username = req.params.username;

User.findOneAndUpdate(
    username, {
        $push: {
            experience: req.body
        }
    }, {
        safe: true,
        upsert: true
    })
    .exec(function (err, data) {
        console.log(data, "------>");
    });
})

This is my schema for experience, which is called in User model like experience: [ExperienceSchema].

const ExperienceSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    company: {
        type: String,
        required: true
    },
    from: {
        type: Date,
    },
    to: {
        type: Date,
    },
    workingNow: {
        type: Boolean,
        default: false
    },
    description: {
        type: String
    }
}, {
    usePushEach: true
})
Krešimir Galić
  • 311
  • 2
  • 14
  • 1
    Did you try adding `new: true` to the `findOneAndUpdate` options? Right after `upsert: true` https://stackoverflow.com/questions/32811510/mongoose-findoneandupdate-doesnt-return-updated-document#answer-32811548 But not sure if this is the issue here, just try – Getter Jetter Nov 02 '18 at 10:48
  • Hm yeah man, now I got the array with new objects, can you please explain? – Krešimir Galić Nov 02 '18 at 10:54
  • Well `findOneAndUpdate` returns by default the original document. If you want the new updated document you need `new: true` thats it. Added answer because it resolved your problem. – Getter Jetter Nov 02 '18 at 10:55

1 Answers1

1

Since findOneAndUpdate returns the original document (state before update) you need to add new: true to the options in order to get the updated document.

options:

{
  safe: true,
  upsert: true,
  new: true
}
Getter Jetter
  • 2,033
  • 1
  • 16
  • 37