如何在同一node.js文件中使用mongo changestream和ws websockets?

时间:2018-10-29 01:31:48

标签: javascript node.js mongodb websocket changestream

我试图通过设置changestream并(使用ws websocket库)将一些更改转发到连接的客户端,来编写一些与当前正在运行的MongoDB数据库一起使用的nodejs代码。

我跟随this guide创建了初始的mongo changestream代码,该代码可以正常工作:

conn = new Mongo("mongodb://localhost:27017/demo?replicaSet=rs");
db = conn.getDB("demo");
collection = db.stock;

const changeStreamCursor = collection.watch(
    [{
        $match: {
            $or: [
                { operationType: "update" },
                { operationType: "insert" }
            ]
        }
    }],
    {
        fullDocument: 'updateLookup'
    }
);

pollStream(changeStreamCursor);
out each change as it comes in
function pollStream(cursor) {
    while (!cursor.isExhausted()) {
        if (cursor.hasNext()) {
            change = cursor.next();
            print(JSON.stringify(change));
        }
    }
    pollStream(cursor);
}

然后我使用mongo脚本运行此文件:

~/Mongo/bin/mongo change-stream-socket-server.js

因此,我基本上想在上面使用此代码,但要添加websockets并调用ws.send(),而不仅仅是将更改记录到控制台。

问题是,但是,似乎无法在mongo脚本执行的javascript文件中使用“ require”。有什么办法让它添加ws依赖项或能够使用require?

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8040 });

conn = new Mongo("mongodb://localhost:27017/");
db = conn.getDB("demo");
collection = db.stock;

const changeStreamCursor = collection.watch(
    [{
        $match: {
            $or: [
                { operationType: "update" },
                { operationType: "insert" }
            ]
        }
    }],
    {
        fullDocument: 'updateLookup'
    }
);



console.log('also setting up websockets...')

wss.on('connection', function connection(ws) {

        wss.clients.forEach(function each(client) {

        pollStream(changeStreamCursor);

        function pollStream(cursor) {

            while (!cursor.isExhausted()) {
                if (cursor.hasNext()) {
                    change = cursor.next();
                    print(JSON.stringify(change));
                    client.send(JSON.stringify(change))
                }
            }
            pollStream(cursor);
        }

    });
});

console.log('server running, waiting for connections...')

当我使用mongo运行它时,此输出显示错误,“未定义要求”:

  

MongoDB Shell版本v3.6.4连接到:mongodb://127.0.0.1:27017   MongoDB服务器版本:3.6.4 2018-10-28T21:23:53.515-0400 E QUERY
  [thread1] ReferenceError:未定义require:   @ change-stream-socket-server.js:2:7加载失败:   change-stream-socket-server.js

如果我尝试仅使用“ node”和文件运行它,则会收到未定义Mongo的错误。我尝试使用带有以下代码的“ MongoClient”连接到它,但这对我也不起作用。

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
const dbName = 'demo';
const client = new MongoClient(url);

client.connect(function(err) {
    assert.equal(null, err);
    console.log("Connected successfully to server");

    const db = client.db('demo');

    const changeStreamCursor = db.collection('stock').watch();

    pollStream(changeStreamCursor);

    function pollStream(cursor) {
    while (!cursor.isExhausted()) {
        if (cursor.hasNext()) {
            change = cursor.next();
            print(JSON.stringify(change));
        }
    }
    pollStream(cursor);
}

});

上面的代码给我输出错误,提示“ cursor.isExhausted不是函数”:

  

(节点:4590)DeprecationWarning:当前URL字符串解析器为   已过时,将在以后的版本中删除。使用新的   解析器,将选项{useNewUrlParser:true}传递给MongoClient.connect。   已成功连接到服务器   /Users/jim/Git-Projects/MongoDB-Change-Streams-Example/node_modules/mongodb/lib/operations/mongo_client_ops.js:466         犯错         ^

     

TypeError:cursor.isExhausted不是函数       在pollStream(/Users/jim/Git-Projects/MongoDB-Change-Streams-Example/basic-mongo-changesream-watcher.js:68:17)       在/Users/jim/Git-Projects/MongoDB-Change-Streams-Example/basic-mongo-changesream-watcher.js:47:2       结果(/Users/jim/Git-Projects/MongoDB-Change-Streams-Example/node_modules/mongodb/lib/utils.js:414:17)       在executeCallback(/Users/jim/Git-Projects/MongoDB-Change-Streams-Example/node_modules/mongodb/lib/utils.js:406:9)       在err(/Users/jim/Git-Projects/MongoDB-Change-Streams-Example/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5)       在connectCallback(/Users/jim/Git-Projects/MongoDB-Change-Streams-Example/node_modules/mongodb/lib/operations/mongo_client_ops.js:241:5)       在process.nextTick(/Users/jim/Git-Projects/MongoDB-Change-Streams-Example/node_modules/mongodb/lib/operations/mongo_client_ops.js:463:7)       在_combinedTickCallback(内部/进程/next_tick.js:131:7)       在process._tickCallback(internal / process / next_tick.js:180:9)

我有什么办法可以同时使用Mongo changestreams和ws websocket库?谢谢!

0 个答案:

没有答案