问题描述
在我的 Meteor 应用程序中,我在 publish
中做了一个 observe
,在某些条件下插入一些新数据.关键是有时我们有重复订阅,竞争条件导致我们重复插入的数据.如果不可能有单一观察者":
In my Meteor application, I made an observe
within a publish
, that insert some new data in certain conditions. The point is that sometimes we have duplicated subscriptions, and race condition leads us to duplicate inserted data.If it is not possible to have "singleton observers":
- 我们如何避免竞争条件和数据库中重复插入的数据?
示例:
Meteor.publish("fortuneUpdate", function () {
var selector = {user: this.userId, seen:false};
DailyFortunes.find(selector).observe({
removed: function(doc, beforeIndex){
if(DailyFortunes.find(selector).count()<1)
createDailyFortune(this.userId);
}
});
}
此问题已从cursor.observe 的工作原理以及如何避免多个实例运行?
推荐答案
据汤姆,这是不可能的,现在,确保共享具有相同参数的 subscribe 调用.因此,如果您遇到与我相同的问题,即观察者内部创建的冗余数据,作为解决方法,我建议您:
According to Tom, it is not possible, for now, to ensure that calls to subscribe that have the same arguments are shared.So, if you are having the same problem I had, of redundant data created inside observers, I suggest you, as workaround, to:
- Create robust indexes that prevent repeted data creating. Compound Keys is probable what you need here.
- Treat duplicate key error exceptions inside your observer ignoring race conditions.
示例:
Collection.find(selector).observe({
removed: function(document){
try {
// Workaround to avoid race conditions > https://stackoverflow.com/q/13095647/599991
createNewDocument();
} catch (e) {
// XXX string parsing sucks, maybe
// https://jira.mongodb.org/browse/SERVER-3069 will get fixed one day
if (e.name !== 'MongoError') throw e;
var match = e.err.match(/^E11000 duplicate key error index: ([^ ]+)/);
if (!match) throw e;
//if match, just do nothing.
}
self.flush();
}
});
这篇关于如何避免 cursor.observe 上的竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!