node.js - 禁用 Mongoose 架构中的插件

标签 node.js mongoose plugins

我正在使用 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/

相关文章:

javascript - Nestjs/cqrs - 类型错误 : Cannot read property 'values' of undefined on install

node.js - Mongoose 错误 : You can not `mongoose.connect()` multiple times while connected

java - Eclipse 的免费 UML 工具/插件可以生成 Java 代码吗?

node.js - 复杂的 Promise 序列 - 嵌套

JavaScript 从文件中读取

html - 如何在 Electron 应用程序中使 Angular 变圆

node.js - MongoDB - $nin 聚合运算符无效

javascript - 在带有 Node.js 的 Mongoose 中使用虚拟 getter 是否会对性能产生影响?

python - 如何将 Composer 项目发送到 QGIS 底部?

grails - spring-security-core 插件的依赖问题