title: NodeJS,MongoDB - Return a JSON response from aggregate inside a GET request
body: <p>I created an aggregate pipeline that returns many documents from my database.I can also see the results using &quot;console.log&quot; .But i can't return the results in a response when i am using Postman.You can test it on PostMan using AreaName=Hungary,Resolution=PT15M,Year=2018,Month=1,Day=1</p>
  <pre class="lang-js prettyprint-override"><code>
  
  var express = require('express');
  var router = express.Router();
  var assert = require('assert')
  const URL = 'mongodb+srv://user:user@cluster0-0pwss.mongodb.net/test?retryWrites=true&amp;w=majority'
  const MongoClient = require('mongodb').MongoClient
  //const CircularJSON = require('circular-json');
  //const {parse, stringify} = require('flatted/cjs');
  
  
  
  router.get('/:AreaName/:Resolution/:Year/:Month/:Day', (req, res, next) =&gt; {
    const _AreaName=req.params.AreaName
    const _Resolution=req.params.Resolution
    const _Year = parseInt(req.params.Year)
    const _Month = parseInt(req.params.Month)
    const _Day = parseInt(req.params.Day)
  
    MongoClient.connect(URL,{
      useNewUrlParser: true,
      useUnifiedTopology: true}, 
      async (err, client) =&gt; {
        if (err) throw err; 
        else console.log('connected to db');
        assert.equal(null, err) 
        const db = client.db('energy')
        var collection = db.collection('ActualTotalLoad')
        const agg = [
          { 
            $match : 
            {
              AreaName: _AreaName,
              Day : _Day,
              Month: _Month,
              Year: _Year
            }
        },
          
          {
            $lookup:
            {
              from: 'ResolutionCode',
              localField: 'ResolutionCodeId',
              foreignField : 'Id',
              as: &quot;resolution_codes&quot;
            }
          },
          {
            $unwind: {path : &quot;$resolution_codes&quot;}
          },
  
          { 
            $match : {'resolution_codes.ResolutionCodeText' : _Resolution}
          },
          {
            $addFields : {ResolutionCode : '$resolution_codes.ResolutionCodeText',
                          Source :'entso-e',
                          Dataset :'ActualTotalLoad'
          }
          },
  
          {
            $project : 
            {
              _id:0,
              Id : 1,
              ResolutionCodeId:1,
              Source : 1,
              AreaName: 1,
              Year : 1,
              Month : 1,
              Day : 1,
              ResolutionCode : 1
            }
          }  
        ];
        var cursor = collection.aggregate(agg)
        cursor.forEach(doc =&gt; {
          console.log(doc)
        })
      
        
       await cursor.toArray((error, result) =&gt; {
          if(error) {
              return res.status(500).send(error);
          }
          cursor.forEach(doc =&gt; {
              res.send(doc)
            })
  
      });
  
    })// connection ends here
  })
  module.exports = router;
  
  </code></pre>
  <p>-&gt; above code gives returns a json and then the server crushes</p>
  <p>I can see the restults of
  &quot;  <em>cursor.forEach(doc =&gt; {
  console.log(doc)})</em>  &quot;
  in the terminal and this seems to be working ok.What i am asking is how to return a response in json.Something like &quot; <em>res.json(cursor)</em> &quot;   I tried some different functions/methods to do this but none seems to work.</p>
  <p><strong>Update</strong>
  After an answer i tried this</p>
  <pre class="lang-js prettyprint-override"><code>cursor.toArray((error, result) =&gt; {
          if(error) {
              return res.status(500).send(error);
          }
          cursor.forEach(doc =&gt; {
              res.send(doc)
            })
      
      });
  
  </code></pre>
  <p>The above code when tested with Postman returns 1 json document from the database.The problem is that it returns only one and then the server crashes.The documents i want to return are multiple. The error message is <em>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client</em></p>