简体   繁体   中英

How to read data in collection in MongoDB?

I am working on a social media app using Node.js and MongoDB. I've got a problem with reading the data in the collection. I want to get everything from the collection.

Router.js:

router.get('/feed', async (req,res) => {
    try{
        await db.client.connect()
        await db.feed(db.client)
        res.render("feed")
    }catch(err){
        console.log(err)
    }finally{
        db.client.close()
    }
})

Db.js

async function feed(client, res){
    let result = await client.db('secret_db').collection('secrets')
    console.log(result)
}

Output:

Collection {
  s: {
    db: Db { s: [Object] },
    options: {
      raw: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {},
      writeConcern: [WriteConcern],
      readPreference: [ReadPreference]
    },
    namespace: MongoDBNamespace { db: 'secret_db', collection: 'secrets' },
    pkFactory: { createPk: [Function: createPk] },
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    },
    bsonOptions: {
      raw: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {}
    },
    readConcern: undefined,
    writeConcern: WriteConcern { w: 'majority' },
    slaveOk: false
  }
}

Take into consideration that I don't have a problem with rendering the pages. The problem must be done inside the async function feed()

You need to use find method of the collection to get the actual data from the DataBase. In your case try this.

 let result = await client.db('secret_db').collection('secrets').find({})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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