8

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

Dr. Mian
  • 3,334
  • 10
  • 45
  • 69
  • It's not JSON, it's BSON. And it's a JavaScript Object because you are using JavaScript. Of course you need to parse.\ – Neil Lunn Jun 09 '17 at 11:53
  • On client side or server side? – Dr. Mian Jun 09 '17 at 12:07
  • Well in you server program connecting to MongoDB. If you are using express then there is [`res.json()`](https://expressjs.com/en/api.html#res.json). Also it it's nodejs then `.toArray()` requires a callback or promise resolution. – Neil Lunn Jun 09 '17 at 12:09
  • I am using express and setup graphql API. The API in its GraphiQL windows respond fine but when I tried to fetch from client side I got an error. Let me add the fetch code too. Probably it will make more sense however ideally I would like to do it on server so that clients dont go through it – Dr. Mian Jun 09 '17 at 12:15
  • Just stringify the object... – Andrew Li Jun 11 '17 at 23:38

3 Answers3

4

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)))
flup
  • 26,937
  • 7
  • 52
  • 74
Dr. Mian
  • 3,334
  • 10
  • 45
  • 69
0

The following snippet will works properly.

fetch('/users.json')
.then(function(response) {
    return response.json()
}).then(function(json) {
    console.log('parsed json', json)
}).catch(function(ex) {
    console.log('parsing failed', ex)
})
socrateisabot
  • 837
  • 2
  • 10
  • 28
-3

You can use mongoexport.

In order to perform this operation you need read access to the database.

Eg: mongoexport --db database [--collection traffic] --out file.json

Nino Matos
  • 91
  • 9