如何将mongodb响应数组从javascript对象转换为JSON字符串

[英]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

我编写了一个javascript API,可以根据请求从mongodb数据库返回所有数据。然而,它正在向数据发送一个对象数组,我想得到简单的json字符串。返回对象的语句是

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.

我是否需要附加另一个函数,如JSON.stringify()?但我认为这对单个对象起作用,但不适用于我的情况下的对象数组。

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

3 个解决方案

#1


4  

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

好的,我找到了解决方案。我只需要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)))

#2


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

#3


-3  

You can use mongoexport.

你可以使用mongoexport。

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

要执行此操作,您需要对数据库的读访问权限。

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

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


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/06/09/fd4225f061d3cd9bf6e37a6f45134d77.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号