Search code examples
node.jsmongodbrxjsreactivex

How to return an observable.fromEvent from a mongo cursor query?


I have a function that does a query and returns an observable from the cursor event that the query returns:

exports.query_tokens = (db) => {
  var req = db.collection('collectionName').find({});
  return Rx.Observable.fromEvent(req, 'data');
}

And I'm using it like this:

...
do(mongo_functions.query_tokens).
subscribe(console.log);

But I'm getting this in the console:

Db {
nodejs                    |   domain: null,
nodejs                    |   _events: {},
nodejs                    |   _eventsCount: 0,
nodejs                    |   _maxListeners: undefined,
nodejs                    |   s: 
nodejs                    |    { databaseName: 'myDatabase',
nodejs                    |      dbCache: {},
nodejs                    |      children: [],
nodejs                    |      topology: 
nodejs                    |       Server {
nodejs                    |         domain:
...

As you can see, they're not my documents. What I'm doing wrong?

As you can see, the Curso actually fires an event called data: http://mongodb.github.io/node-mongodb-native/3.0/api/Cursor.html#event:data


Solution

  • The do operator receives the observable's next, error and complete notifications, but has no effect on the observable. That is, any value returned from the do operator's next function is ignored. Consequently, the function passed to subscribe receives the Db.

    Instead of do, you most likely want to use switchMap, to flatten the event observable into the observable stream:

    ...
    .switchMap(mongo_functions.query_tokens)
    .subscribe(console.log);