title: Send MongoDB query result as JSON using express
body: <p>I'm writing an application where I use express, Node.js and MongoDB (using mongojs). I have a module <code>db.js</code> and a <code>server.js</code>, which have the snippets below.</p>
  
  <p><strong>db.js</strong></p>
  
  <pre><code>var getUsersByCity = function(city, callback) {
      db.users.find({'city': city}).toArray(function(err, data) {
          if (err) {
              callback(err);
              console.log(err);
          } else {
              console.log(data);
              callback.json(data);
          }
      });
  }
  </code></pre>
  
  <p><strong>server.js</strong></p>
  
  <pre><code>app.post("/get_users_list", function(req, res) {
      var body = req.body;
      db.getUsersByCity(body.city, res);
  });
  </code></pre>
  
  <p>It's working because, as you can see, I'm (probably incorrectly) using <code>callback.json(data)</code>, when I should be using <code>callback(data)</code>. I think the <code>db.js</code> module should not be responsible for sending the response and I should pass <code>res.json</code> as the callback to my function.</p>
  
  <p>The problem is: when I do things the way I consider right, I face the following error:</p>
  
  <pre><code>path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js:245
          throw message;      
                ^
  TypeError: Cannot call method 'get' of undefined
      at res.json (path_to_my_app/node_modules/express/lib/response.js:189:22)
      at path_to_my_app/db.js:36:13
      at path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js:163:16
      at commandHandler (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/cursor.js:706:16)
      at path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/db.js:1843:9
      at Server.Base._callHandler (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
      at path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js:468:18
      at MongoReply.parseBody (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
      at null.&lt;anonymous&gt; (path_to_my_app/node_modules/mongojs/node_modules/mongodb/lib/mongodb/connection/server.js:426:20)
      at EventEmitter.emit (events.js:95:17)
  </code></pre>
  
  <p>How to properly send the JSON response without sending the response object to my DB module?</p>
  
  <p><strong>P.S.</strong> The content of line 36 of <code>db.js</code>, when I make the changes, is <code>callback(data);</code>.</p>