【问题标题】:Unable to create watch on multiple collections mongodb无法在多个集合 mongodb 上创建监视
【发布时间】:2020-10-13 13:36:07
【问题描述】:

我正在尝试使用 mongoose 构造在 MongoDB 中的数据库集合上创建一个手表,

collection.watch({ fullDocument: "updateLookup" })

我的整个功能如下
exports.createWatchOnAuthCollection = (site, type) => {
    if (watchedTypes.includes(type + '_' + site)) {
        console.log('Ignoring.. Already watch added on this type and site ' + type + '_' + site);
        return;
    }
    dbConnectionPool.getDBConnection('auth_' + site, function (dbConnection) {
        if (type == 'unit_status') {
            console.log('Trying to add watch on ' + site);
            var collection = dbConnection.collection('units');
            collection.watch({
                fullDocument: "updateLookup"
            })
                .on('change', function (change) {
                    handleStatusUpdate(site, change);
                })
                .on('error', function (error) {
                    console.log('Got a error reply')
                });
            watchedTypes.push(type + '_' + site);
        } else if (type == 'iatas') {
            
        }
    });
}

我面临的问题是,当我循环此函数调用以在多个集合上创建监视时,只有创建的最新集合上的监视实际上有效,并且调用了回调,而不是在其他集合上。我的调用函数如下

sites.forEach(site => {
    controller.createWatchOnAuthCollection(site, watchType);
})

提前谢谢..:)

【问题讨论】:

    标签: node.js mongodb mongoose changestream


    【解决方案1】:

    您不能使用同一个会话来创建多个更改流侦听器。因此,您需要指定不同的会话或使用不同的连接来打开每个流。

    另外请注意,同时打开许多流可能会对性能产生负面影响,因此建议仅在 dbconnection 对象上打开一个流并过滤掉您要监控的集合。例如:

    ...
    collections = [];
    sites.forEach(site => {
      // For each collection to watch, add a filter in the collections array
      collections.push({ "db": "auth_" + site, "coll": "units" });
    });
    
    // Create a change stream on the deployment and filter only
    // the collections we want
    client.watch([ { "$match": { "ns": { "$in": collections } } } ],
        { "fullDocument": "updateLookup" });
    ...
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多