[英]Mongodb returns an empty array while retrieving data through nodejs
let mongodb = require('mongodb').MongoClient;
let express = require("express")
let app = express()
let connectionString = 'mongodb://ToDoAppUser:ToDoAppUserPassword@ac-u9kgapm-shard-00-00.8rdkdoi.mongodb.net:27017,ac-u9kgapm-shard-00-01.8rdkdoi.mongodb.net:27017,ac-u9kgapm-shard-00-02.8rdkdoi.mongodb.net:27017/?ssl=true&replicaSet=atlas-68qno6-shard-0&authSource=admin&retryWrites=true&w=majority'
let db
mongodb.connect(connectionString,function(err,client){
if (err) throw err
db = client.db()
app.listen(3000)
console.log("Database connected.");
})
app.use(express.urlencoded({extended : false}))
嘗試從 MongodB 檢索數據
如您所見,我正在嘗試從名為#item 的 MongoDB 集合中檢索數據並希望打印它。 但它顯示了一個空數組。 我堅持這一點。 請幫我解決這個問題。
app.get("/", function(req, res){
**// this collectio method of mongodb returns empty array.
// however, mongodb got connected, but i cannot retreive data from mongodb**
db.collection('items').find().toArray(function(err, items) {
if(err) console.log(err)
console.log(items)
})
您需要使用以下格式。
async function findOneListingByName(client, nameOfListing) {
const result = await client.db("sample_airbnb").collection("listingsAndReviews").findOne({ name: nameOfListing });
if (result) {
console.log(`Found a listing in the collection with the name '${nameOfListing}':`);
console.log(result);
} else {
console.log(`No listings found with the name '${nameOfListing}'`);
}
}
上面的代碼對我有用。 順便說一句,您可以在此處閱讀他們的文檔以獲取更多示例: https://www.mongodb.com/developer/languages/javascript/node-crud-tutorial/
我的猜測是從數據庫中獲取項目的調用是異步的,並且您正在嘗試使用項目同步方式。
嘗試將async
添加到 controller function 並使用await
數據庫請求。 像這樣:
app.get("/", async function(req, res){
/* Mongo documents don't show any parameters for the toArray method
* Read here https://www.mongodb.com/docs/manual/reference/method/cursor.toArray/#mongodb-method-cursor.toArray
*
*/
const itemsFromDB = await db.collection('items').find().toArray()
conssole.log('items are:' itemsFromDB )
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.