Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add Lodash guide highlighting issues with cloneDeep() #12609

Merged
merged 1 commit into from Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/guides.md
Expand Up @@ -33,6 +33,7 @@ integrating Mongoose with external tools and frameworks.
### Integrations

* [Promises](/docs/promises.html)
* [Lodash](/docs/lodash.html)
* [AWS Lambda](/docs/lambda.html)
* [Browser Library](/docs/browser.html)
* [GeoJSON](/docs/geojson.html)
Expand Down
39 changes: 39 additions & 0 deletions docs/lodash.md
@@ -0,0 +1,39 @@
# Using Mongoose with Lodash

For the most part, Mongoose works well with [Lodash](https://lodash.com/).
However, there are a few caveats that you should know about.

* [`cloneDeep()`](#clonedeep)

## `cloneDeep()`

You should not use [Lodash's `cloneDeep()` function](https://lodash.com/docs/4.17.15#cloneDeep) on any Mongoose objects.
This includes [connections](./connections.html), [model classes](./models.html), and [queries](./queries.html), but is _especially_ important for [documents](./documents.html).
For example, you may be tempted to do the following:

```javascript
const _ = require('lodash');

const doc = await MyModel.findOne();

const newDoc = _.cloneDeep(doc);
newDoc.myProperty = 'test';
await newDoc.save();
```

However, the above code will throw the following error if `MyModel` has any array properties.

```no-highlight
TypeError: this.__parentArray.$path is not a function
```

This is because Lodash's `cloneDeep()` function doesn't [handle proxies](https://stackoverflow.com/questions/50663784/lodash-clonedeep-remove-proxy-from-object), and [Mongoose arrays are proxies as of Mongoose 6](https://thecodebarbarian.com/introducing-mongoose-6.html#arrays-as-proxies).
You typically don't have to deep clone Mongoose documents, but, if you have to, use the following alternative to `cloneDeep()`:

```javascript
const doc = await MyModel.findOne();

const newDoc = new MyModel().init(doc.toObject());
newDoc.myProperty = 'test';
await newDoc.save();
```
1 change: 1 addition & 0 deletions docs/source/index.js
Expand Up @@ -62,6 +62,7 @@ exports['docs/jobs.pug'] = {
jobs
};
exports['docs/change-streams.md'] = { title: 'MongoDB Change Streams in NodeJS with Mongoose', markdown: true };
exports['docs/lodash.md'] = { title: 'Using Mongoose with Lodash', markdown: true };

for (const props of Object.values(exports)) {
props.jobs = jobs;
Expand Down