簡體   English   中英

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

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM