将 Mongoose 与 Lodash 结合使用

¥Using Mongoose with Lodash

大多数情况下,Mongoose 与 Lodash 配合良好。但是,你应该了解一些注意事项。

¥For the most part, Mongoose works well with Lodash. However, there are a few caveats that you should know about.

cloneDeep()

你不应该在任何 Mongoose 对象上使用 Lodash 的 cloneDeep() 函数。这包括 connections模型类queries,但对于 documents 尤其重要。例如,你可能想做以下事情:

¥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();

但是,如果 MyModel 具有任何数组属性,上述代码将引发以下错误。

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

TypeError: this.__parentArray.$path is not a function

这是因为 Lodash 的 cloneDeep() 功能没有 处理代理Mongoose 数组是 Mongoose 6 的代理。你通常不必深度克隆 Mongoose 文档,但如果必须,请使用以下 cloneDeep() 替代方案:

¥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 cloneDeep():

const doc = await MyModel.findOne();

const newDoc = new MyModel().init(doc.toObject());
newDoc.myProperty = 'test';
await newDoc.save();