0

I have some RxJS code using mongo to perform queries. Works fine in RxJS v4 but as I am migrating to v.5 I am running into issues.

Here's some simplified code:

// Get a mongo connection
getDb() {
  var connect = Rx.Observable.bindNodeCallback(mongodb.connect)
  return connect(this.options.connection.uri, this.options.connection.options)
}

// Query
return getDb()
  .flatMap((db) => {
    var c = db.collection('foo')
    var obs = Rx.Observable.bindNodeCallback(c.insertMany, c)
    return obs(docs)
  })
  .subscribe(...)

Every time I try some sort of query it fails with various errors. All the errors are related to an options object not existing inside the Mongo code. I think this may be a context issue but I am not sure.

The query above yields (in the code, undefined is a mongo collection options object)

Uncaught TypeError: Cannot read property 'serializeFunctions' of undefined
at BoundNodeCallbackObservable.Collection.insertMany[as callbackFunc](node_modules / mongodb / lib / collection.js: 482: 74)

A similar query yields:

TypeError: Cannot read property 'options' of undefined
at BoundNodeCallbackObservable.Collection.remove[as callbackFunc](node_modules / mongodb / lib / collection.js: 1223: 12)

Update When I wrap it manually things work:

var obs = Rx.Observable.create(function(observer) {
   c.insertMany(docs, function(err, res) {
     if (err) { observer.error(err) } else {
       observer.next(res);
       observer.complet();
      }
    })
  })
  return obs

 // This doesn't:
 var obs = Rx.Observable.bindNodeCallback(c.insertMany, c)
 return obs(docs)
cyberwombat
  • 38,105
  • 35
  • 175
  • 251

1 Answers1

2

Ok. Turns out bindNodeCallback and bindCallback do not allow for context to be passed. So we need to do this:

c.insertMany = c.insertMany.bind(c)
var obs = Rx.Observable.bindNodeCallback(c.insertMany)
cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • This saved me a huge headache. I figured it hand to do with the lexical scoping of 'this' in my code. – Ray Suelzer Apr 23 '17 at 00:52
  • I encountered the same problem with ftp, I just specified ` Rx.Observable(c.ready.bind(c)) ` without changing original object, that may be not wanted, or it does not really care, but it works and is ok – Daniele Cruciani Apr 06 '18 at 15:01