To make
findOneAndUpdate()
return the updated document, you need to use the
returnDocument
option.
returnDocument
has two possible values:
'before'
and
'after'
.
The default behavior is
'before'
, which means returning the document as it was
before
the update was applied.
const testSchema = new mongoose.Schema({
name: String
await Test.create({name: 'Test Testerson'});
await Model.findOneAndUpdate({name: 'Test Testerson'}, {name: 'MasteringJS.io'}, {returnDocument: 'before'});
await Model.findOneAndUpdate({name: 'Test Testerson'}, {name: 'MasteringJS.io'}, {returnDocument: 'after'});
The Time Before
returnDocument
Before
returnDocument
was implemented, there were two similar options:
returnOriginal
or
new
.
Both were booleans that did what
returnDocument
does now.
await Model.findOne(filter, update, {returnOriginal: false});
await Model.findOne(filter, update, {new: true});
Note:
Mongoose still supports
returnOriginal
and
new
.
But
returnDocument
is the recommended approach.
Want to become your team's MongoDB expert? "Mastering Mongoose" distills 8 years of hard-earned
lessons building Mongoose apps at scale into 153 pages. That means you can learn what you need
to know to build production-ready full-stack apps with Node.js and MongoDB in a few days.
Get your copy!