[英]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. 我编写了一个javascript API,可以根据请求从mongodb数据库返回所有数据。 However it is sending the data s an array of objects and I want to get the simple json string. 然而,它正在向数据发送一个对象数组,我想得到简单的json字符串。 The statement returning the objects is 返回对象的语句是
return db.collection('variants').find().toArray();
Do I need to append another function like JSON.stringify()? 我是否需要附加另一个函数,如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)
. 我只需要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. 你可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.