【问题标题】:MongoDB + ExpressJS - Observe insertionsMongoDB + ExpressJS - 观察插入
【发布时间】:2017-11-07 08:11:49
【问题描述】:

我的 mongodb 中有一个快速增长的集合。当新文档插入这些集合时,我想采取某些措施。当插入这样的新模型时,如何观察并触发动作?

我确实发现了诸如 mongo-observer 之类的旧解决方案,但这些解决方案似乎很旧,对我不起作用。

谁能推荐一个相对较新且维护良好的解决方案?

【问题讨论】:

  • 要求我们推荐或查找书籍、工具、软件库、教程或其他非现场资源的问题对于 Stack Overflow 来说是题外话,因为它们往往会吸引固执己见答案和垃圾邮件。取而代之的是describe the problem 以及迄今为止为解决它所做的工作。

标签: node.js mongodb express observer-pattern


【解决方案1】:

schema.pre() 钩子可以做到这一点。示例:

export const schema = new mongoose.Schema({
    name: String,
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    }
}, { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } 
});

schema.pre("save", function (next) {
    bcrypt.hash(this.password, 10, (err, hash) => {
        this.password = hash;
        next();
    });
});

schema.pre("update", function (next) {
    bcrypt.hash(this.password, 10, (err, hash) => {
        this.password = hash;
        next();
    });
});

【讨论】:

  • 该架构上是否还有用于批量操作的前/后挂钩?
  • pre and post hooks 适用于每个更改的文档,因此它们也适用于批量操作。如果您想为整个系列更改某些内容,也许您正在寻找类似migrate
  • 我的情况不需要迁移。我正在将我的对象批量更新到数据库中。每次插入时,我都想触发另一个动作。使用 bulk.find().upsert().update() 时发布“保存”和“更新”以及许多其他内容很遗憾没有触发,只是尝试过。
【解决方案2】:

你可以参考npm模块-mongohooks

更新:

添加示例代码:

const db = require('mongojs')('mydb', ['members']); // load mongojs as normal 
const mongohooks = require('mongohooks');

// Add a `createdAt` timestamp to all new documents 
mongohooks(db.members).save(function (document, next) {
  document.createdAt = new Date();
  next();
});

// Now just use the reqular mongojs API 
db.members.save({ name: "Thomas" }, function (error, result) {
  console.log("Created %s at %s", result.name, result.createdAt);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-13
    • 2018-03-12
    • 1970-01-01
    • 2018-08-09
    • 2010-09-23
    • 1970-01-01
    • 2017-08-07
    • 2021-01-21
    相关资源
    最近更新 更多