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

5
  • It's not JSON, it's BSON. And it's a JavaScript Object because you are using JavaScript. Of course you need to parse.\ Commented Jun 9, 2017 at 11:53
  • On client side or server side? Commented Jun 9, 2017 at 12:07
  • Well in you server program connecting to MongoDB. If you are using express then there is res.json(). Also it it's nodejs then .toArray() requires a callback or promise resolution. Commented Jun 9, 2017 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 Commented Jun 9, 2017 at 12:15
  • Just stringify the object... Commented Jun 11, 2017 at 23:38

3 Answers 3

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

Sometimes... The simplest answer is the one you already know ;)
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)
})

Comments

-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.