Search code examples
javascriptjsonmongodbbson

How to convert mongodb response array from javascript object to JSON string


I have written a javascript API which returns all the data from mongodb database on request. However it is sending the data s an array of objects and I want to get the simple json string. The statement returning the objects is

return db.collection('variants').find().toArray();

Do I need to append another function like JSON.stringify()? but I think that work for single object but not for array of objects as in my case.

var fetch = require('graphql-fetch');
const API_URL = `http://localhost:4000/graphql`
const query = `
{
  variants{
    VARIANT_ID
    CHROM
  }
}
`
fetch(API_URL)(query).then(data => console.log(data))

enter image description here


Solution

  • Okay I found the solution. All I need is JSON.stringify(data).

    var fetch = require('graphql-fetch');
    const API_URL = `http://localhost:4000/graphql`
    const query = `
    {
      variants{
        VARIANT_ID
        CHROM
      }
    }
    `
    fetch(API_URL)(query).then(data => console.log(JSON.stringify(data)))