简体   繁体   English

Mongodb 通过nodejs检索数据时返回一个空数组

[英]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}))

Trying to retrieve data from MongodB尝试从 MongodB 检索数据

As you can see that, I am trying to retrieve data from MongoDB collection named #item and want to print it.如您所见,我正在尝试从名为#item 的 MongoDB 集合中检索数据并希望打印它。 But it shows an empty array.但它显示了一个空数组。 I am stuck on this.我坚持这一点。 kindly help me to resolve this issue.请帮我解决这个问题。

    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)
    
      })

You need to use the following format.您需要使用以下格式。

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}'`);
    }
}

This code above is worked for me.上面的代码对我有用。 By the way, you can read their documentation here for more examples: https://www.mongodb.com/developer/languages/javascript/node-crud-tutorial/顺便说一句,您可以在此处阅读他们的文档以获取更多示例: https://www.mongodb.com/developer/languages/javascript/node-crud-tutorial/

My guess is that the call to fetch items from DB is asynchronous, and you're trying to use items synchronous manner.我的猜测是从数据库中获取项目的调用是异步的,并且您正在尝试使用项目同步方式。

Try adding async to the controller function and using await for the DB request.尝试将async添加到 controller function 并使用await数据库请求。 Like this:像这样:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM