Q promises and mongoose with connection.insert Q promises and mongoose with connection.insert mongoose mongoose

Q promises and mongoose with connection.insert


This is a pretty common problem, not really to do with Q, but to do with JavaScript in general. The problem is that when you pass functions to other functions, they lose their this context. You would have just as much of a problem if you did, e.g.

var func = RidePaths.collection.insert;func(...); // does not work

The solution is to use .bind:

var func = RidePaths.collection.insert.bind(RidePaths.collection);func(...); // works!

The same thing works in Q, where you're passing RidePaths.collection.insert as a function:

return q.nfcall(RidePaths.collection.insert.bind(RidePaths.collection), ridePaths);

This is of course verbose and ugly, so that's why we provided you with ninvoke, which as you noted works nicely:

return q.ninvoke(RidePaths.collection, 'insert', ridePaths);