Error with $geoNear in Node

Hello- I’m new to Mongo. The following $geoNear query works as expected in Compass, but when I export it to run it in a Twilio Function (Node), I get the following error. The error seems to point out the issue, but as I exported the Node code from Compass I’m not sure how to fix it. Just trying to get it to run right now and any help would be greatly appreciated.

as an FYI, I can get $near query’s to run as expected in Twilio Functions but can’t figure out this aggregation query.


{“message”:“Argument “options” must not be function”,“name”:“MongoInvalidArgumentError”,“stack”:“MongoInvalidArgumentError: Argument “options” must not be function\n at Collection.aggregate (/var/task/node_modules/mongodb/lib/collection.js:371:19)\n at /var/task/handlers/ZN438f1f783d743f6e2a9d6fc330fe0a1d.js:31:16\n at /var/task/node_modules/mongodb/lib/utils.js:510:9\n at /var/task/node_modules/mongodb/lib/mongo_client.js:130:17\n at connectCallback (/var/task/node_modules/mongodb/lib/operations/connect.js:29:9)\n at /var/task/node_modules/mongodb/lib/operations/connect.js:80:9\n at /var/task/node_modules/mongodb/lib/sdam/topology.js:219:25\n at /var/task/node_modules/mongodb/lib/cmap/connection_pool.js:273:25\n at handleOperationResult (/var/task/node_modules/mongodb/lib/sdam/server.js:363:9)\n at MessageStream.messageHandler (/var/task/node_modules/mongodb/lib/cmap/connection.js:474:9)”}

// running in Twilio Function

exports.handler = function(context, event, callback) {
  const MongoClient = require('mongodb').MongoClient;
  const assert = require('assert');

  const agg = [
      '$geoNear': {
        'near': {
          'type': 'Point', 
          'coordinates': [
            -77.41702, 43.09166
        'distanceField': 'dist.calculated', 
        'includeLocs': 'dist.location', 
        'spherical': true
    }, {
      '$limit': 3

    { useNewUrlParser: true, useUnifiedTopology: true },
    function(connectErr, client) {
      assert.equal(null, connectErr);
      const collection = client.db('customerRouter').collection('serviceCenters');
      collection.aggregate(agg, (cmdErr, result) => {
        assert.equal(null, cmdErr);

    return callback(null, "test");


It looks like it thinks the second argument is options - do you get the same error if you pass it an options object (you could use an option with its default value not to change the actual execution of the aggregation, like {"readPreference":"primary"} or something like that).