Using Mongoose with Lodash
For the most part, Mongoose works well with Lodash. However, there are a few caveats that you should know about.
You should not use Lodash's
cloneDeep() function on any Mongoose objects.
This includes connections, model classes, and queries, but is especially important for documents.
For example, you may be tempted to do the following:
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.
TypeError: this.__parentArray.$path is not a function
This is because Lodash's
cloneDeep() function doesn't handle proxies, and Mongoose arrays are proxies as of Mongoose 6.
You typically don't have to deep clone Mongoose documents, but, if you have to, use the following alternative to
const doc = await MyModel.findOne(); const newDoc = new MyModel().init(doc.toObject()); newDoc.myProperty = 'test'; await newDoc.save();