[英]How to get the JSON object after collection.find()
我正在使用 nodeJS 通過 URL 從mongoatlas
獲取數據。
但是,在 function collection.find()
之后,我不知道如何將我得到的數據轉換為 JSON object ,然后再進行stringify()
。
變量record
未定義,我不知道如何正確分配它。
代碼如下:
app.get("/allbooks", (request, response) => {
console.log("someone request to get all books from database")
var records = collection.find()
if(records!=null){
console.log('not empty')
}
var result
records.forEach(function(record) {
if(record!=null) {
console.log(record)
result = result + JSON.stringify(record)
}
}, function(err) {
if(err) {
response.status(500).send(err)
}
console.log(result)
response.send(result)
})
})
如我所見,收集方法“查找”返回 promise,請嘗試等待。
const records = await collection.find();
console.log(records);
另外,檢查此方法的接口,它可以將回調 fn 作為參數。
使用lean
const records = await collection.find().lean()
這將產生一個 json object,然后可以輕松地對其進行字符串化。
您可以像這樣更改和簡化代碼:
app.get("/allbooks", async (request, response) => {
try {
let records = await collection.find({});
res.status(200).send(JSON.stringify(records));
} catch (error) {
res.status(400).json({ error: error });
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.