是否可以从Meteor读取所有数据库操作?

时间:2015-02-12 17:35:32

标签: javascript mongodb meteor

如果我设置了这样的数据库:

@Apples = new Meteor.Collection 'apples'

有没有办法在每次对苹果进行数据库操作时设置要调用的函数? E.g。

Apple.update {name: 'Frank'}

导致这样的事情被称为:

appleOperation = (operation, parameter) ->
    # Log the operation in another database
    # Continue with the database operation

2 个答案:

答案 0 :(得分:1)

我相信您可能正在寻找游标 .observe和/或游标 .observeChanges。请原谅我没有使用Coffeescript

Apples = new Meteor.Collection("apples");

Apples.find().observe({
    added: function(document) {
        // Do stuff with the added document
    },
    changed: function(newDoc, oldDoc) {
        // Do stuff with the old and new document
    },
    removed: function(document) {
        // Do stuff with the removed document
    }
});

如果您现在添加文档:

Apples.insert({name: "Frank"});

添加的函数将使用Frank插入的任何ID调用,{name:“Frank”}作为fields-parameter。

与observeChanges类似,后者仅为您提供更改的字段

Apples.find().observeChanges({
    added: function(id, fields) {
        // Do stuff with the added document
    },
    changed: function(id, fields) {
        // Do stuff with the changed fields
    },
    removed: function(id) {
        // Do stuff with the id of the removed document
    }
});

请参阅Meteor documentation

答案 1 :(得分:1)

是的,并且有一个很好的方案来处理所有细节:

https://github.com/matb33/meteor-collection-hooks