简体   繁体   中英

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))

在此输入图像描述

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)))

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)
})

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM