Categories
JavaScript Answers

How to turn a Mongoose document into a plain object?

Spread the love

Sometimes, we want to turn a Mongoose document into a plain object.

In this article, we’ll look at how to turn a Mongoose document into a plain object.

How to turn a Mongoose document into a plain object?

To turn a Mongoose document into a plain object, we can use the lean method.

For instance, we write

MyModel.findOne().lean().exec((err, doc) => {
  doc.addedProperty = 'foobar';
});

to call lean on the document returned by findOne.

Then we get the plain object version of the document from doc in the callback that we call exec with.

Conclusion

To turn a Mongoose document into a plain object, we can use the lean method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *