[英]Want to call an api to get the data from mongodb in json format but getting in raw format, using javascript, node.js, express, mongodb
这就是我连接到数据库的方式:
> //Connecting Mongodb using mongoclient
>
> const MongoClient = require('mongodb').MongoClient
>
> const url = 'url is used'
>
> const dbName = 'virtualcso'
>
> let db
>
> // Conforming the database is connected
>
> MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
>
> if (err) return console.log(err)
>
> // Storing a reference to the database so you can use it later
>
> db = client.db(dbName)
>
> console.log(`Connected MongoDB: ${url}`)
>
> console.log(`Database: ${dbName}`) })
这是 api 调用
> // api to fetch the data from the Mongodb
>
> app.get('/fetch', function (req, res) {
>
> // getting all the data
>
> db.collection('sectester_zap')
>
> .find()
>
> .toArray(function (err, items) {
>
> res.json(items);
>
> }) })
这就是我得到结果的方式**
[{"_id":"600bc689bee1c602a89713d1","@version":"2.10.0","@generated":"2021 年 1 月 13 日星期三 20:21:56","site":[{"@name": "http://demo.testfire.net","@host":"demo.testfire.net","@port":"80","@ssl":"false","alerts":[{" pluginid":"10021","alertRef":"10021","alert":"X-Content-Type-Options Header Missing","name":"X-Content-Type-Options Header Missing","riskcode" :"1","信心":"2","riskdesc":"低(中)","desc":"
防 MIME 嗅探 header X-Content-Type-Options 未设置为“nosniff”。 这允许旧版本的 Internet Explorer 和 Chrome 对响应正文执行 MIME 嗅探,可能导致响应正文被解释并显示为声明的内容类型以外的内容类型。 当前(2014 年初)和旧版本的 Firefox 将使用声明的内容类型(如果设置了),而不是执行 MIME 嗅探。
","instances":}}]}]我需要以 json 格式获取此数据*
在不熟悉 MongoDB 的情况下,从外观上看,您将得到 JSON 的结果,然后将其放入数组中。
从我周围的情况来看, .find() 将以 JSON 格式将 cursor 返回到所有文档,因此请考虑您是否真的需要在解决方案中使用 .toArray() 。
我在这里查看了其他内容: https://www.guru99.com/mongodb-query-document-using-find.html他们在 example.forEach(printjson) 中使用来显示他们的结果。
您添加这个来测试 output 的示例如下所示:
// api 从 Mongodb 获取数据
app.get('/fetch', function (req, res) {
// getting all the data db.collection('sectester_zap').find().forEach(printjson)
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.