title: How to return JSON from MongoDB in Node.js?
body: <p>I have a mongodb database called <code>pokemon</code> with a collection called <code>pokemons</code>. Here is my attempt to write a function that will do a <code>find()</code> operation in mongodb: </p>
  
  <pre><code>'use strict';
  
  var MongoClient = require('mongodb').MongoClient;
  var assert = require('assert');
  
  // db url
  var url = 'mongodb://localhost:27017/pokemon';
  
  exports.getPokemonByName = function (name) {
  
    MongoClient.connect(url, function(err, db) {
      assert.equal(null, err);
      var cursor = db.collection('pokemons').find({name: name});
  
      // how to return json? 
    });
  
  };
  </code></pre>
  
  <p>I then call this function in another file: </p>
  
  <pre><code>var express = require('express');
  var router = express.Router();
  
  router.get('/pokedex', function (req, res) {
    res.jsonp(db.getPokemonByName('Dratini'));
  })
  </code></pre>
  
  <p><a href="https://docs.mongodb.org/getting-started/node/query/" rel="noreferrer">This link</a> is helpful in showing how to log mongodb data to the console by doing some sort of <code>each()</code> method on the cursor object, but I don't know how to <code>return</code> json through the <code>getPokemonByName</code> function. I tried to define an empty array on the root scope of the <code>getPokemonByName</code> function and push data into that array with each iteration of the <code>.each</code> method show in that link, but I think I still can't return that array because it happens after the fact. </p>
  
  <p>BTW, I'm really just doing this for fun and to learn about MongoDB and Node.js, so I don't want to use or an ODM like Mongoose to do some of this work for me. </p>