Mongodb在通过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/

我的猜测是,从DB中提取项的调用是异步的,您正试图使用项同步方式。

尝试将async添加到控制器函数,并对DB请求使用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 )
})

最新更新