繁体   English   中英

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

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

我正在使用 Node.js 和 MongoDB 开发社交媒体应用程序。 我在读取集合中的数据时遇到问题。 我想从收藏中得到所有东西。

路由器.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()
    }
})

数据库.js

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

输出:

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

考虑到我在渲染页面方面没有问题。 问题必须在异步函数 feed() 内完成

您需要使用集合的find方法从数据库中获取实际数据。 在你的情况下试试这个。

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

暂无
暂无

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

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