简体   繁体   English

如何在MongoDB中读取集合中的数据?

[英]How to read data in collection in MongoDB?

I am working on a social media app using Node.js and MongoDB.我正在使用 Node.js 和 MongoDB 开发社交媒体应用程序。 I've got a problem with reading the data in the collection.我在读取集合中的数据时遇到问题。 I want to get everything from the collection.我想从收藏中得到所有东西。

Router.js:路由器.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数据库.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()问题必须在异步函数 feed() 内完成

You need to use find method of the collection to get the actual data from the DataBase.您需要使用集合的find方法从数据库中获取实际数据。 In your case try this.在你的情况下试试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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