Mongoose: findOneAndUpdate with {upsert: true} does not return document

Created on 29 Apr 2015  ·  4Comments  ·  Source: Automattic/mongoose

Recently upgraded to mongoose 4.0.2. The following code was working previously, but now results in the document being created but not passed to the callback:

Milestone.findOneAndUpdate({
    ......
}, {
    ......
}, {upsert: true}, function(err, res) {
    // err === null
    // res === null
    done(err, res);
});

This is only occurring on upsert. I can verify the document is created, but both err and res are consistently null. If I call the function again (now that the document exists) it works as expected.

mongoose: 4.0.2
node: v0.12.2
mongodb: 2.6.9

help

Most helpful comment

Use the new: true option, see 4.0 release notes notes on #2262.

Milestone.findOneAndUpdate({
    ......
}, {
    ......
}, {upsert: true, 'new': true}, function(err, res) {
    // err === null
    // res === null
    done(err, res);
});

All 4 comments

Use the new: true option, see 4.0 release notes notes on #2262.

Milestone.findOneAndUpdate({
    ......
}, {
    ......
}, {upsert: true, 'new': true}, function(err, res) {
    // err === null
    // res === null
    done(err, res);
});

Thanks! Why does the document still get created if I leave out new: true?

new is false by default, and when new is false MongoDB returns the document as it was before the update operation was applied. In the case of upserts, there was no document, hence null.

Ah I see, thank you!

Was this page helpful?
0 / 5 - 0 ratings