我正在使用 Mongoose 插件 (mongoose-patch-history),它会自动跟踪 MongoDB 集合模型的更改。我需要有选择地禁用该插件(即,我只想根据标志/标准跟踪某些模型的更改,而不是其他模型的更改)。 我相信我需要插件中的某种过滤功能,但它没有为此提供机制。 我还有其他方法可以实现这一目标吗?
最佳答案
插件在架构上设置中间件。就我而言,插件timestamp
注册了这个中间件
schema.pre('findOneAndUpdate', function (next) {
if (this.op === 'findOneAndUpdate') {
this._update = this._update || {};
this._update[updatedAt] = new Date;
this._update['$setOnInsert'] = this._update['$setOnInsert'] || {};
this._update['$setOnInsert'][createdAt] = new Date;
}
});
我无法从架构中删除此中间件(这里有 answer 关于如何访问注册的中间件)。
解决方案
我使用完全相同的 SchemaType 创建了 Schema 的新实例。我避免了添加插件。
要创建具有相同 schemaType 的架构,只需访问属性 paths
import _ from 'lodash'
import mongoose from 'mongoose'
// schema with plugin
import EntitySchema from '../entity.model'
// creating clone of paths for cleanliness
const schemaType = _.cloneDeep(EntitySchema.paths)
// new schema, free of plugins
const newSchema = new mongoose.Schema(schemaType)
关于node.js - 禁用 Mongoose 架构中的插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53264539/