如何从MongoDB获取文档?

时间:2019-06-22 16:44:19

标签: node.js mongodb mongodb-query

我在MongoDB Atlas上有一个数据库。 使用NodeJS,我建立了一个连接并尝试获取一些数据。

const client = new MongoClient(uri, { useNewUrlParser: true });
    client.connect(err => {

        if(err){
            console.log(err)
            return res.status(400).json({msg:"Error occured while trying to connect to database", error: err})
        }
        const collection = client.db("first-test").collection("members")
        // perform actions on the collection object
        // console.log(collection)
        collection.forEach(member => {
            console.log(member)
        })
        client.close();
        return res.status(200).json({msg:"success"})
    });

当我尝试console.log(collection)时,有一个大对象作为输出(我想这就是所谓的游标)

Collection {
  s: {
    pkFactory: [Function: ObjectID] {
      index: 4705316,
      createPk: [Function: createPk],
      createFromTime: [Function: createFromTime],
      createFromHexString: [Function: createFromHexString],
      isValid: [Function: isValid],
      ObjectID: [Circular],
      ObjectId: [Circular]
    },
    db: Db {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      s: [Object],
      serverConfig: [Getter],
      bufferMaxEntries: [Getter],
      databaseName: [Getter]
    },
// And so on ....

尝试collection.forEach(member => console.log(member))时遇到错误TypeError: collection.forEach is not a function。我的问题是,如何从数据库中获取数据?

2 个答案:

答案 0 :(得分:1)

您缺少“查找”所有文档的步骤。

来自w3schools的:

  dbo.collection("customers").find({}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });

答案 1 :(得分:1)

我建议使用猫鼬,这要简单得多。

但是实际的代码是

const client = new MongoClient(uri, { useNewUrlParser: true });
    client.connect(err => throw err);

client.members.find({},(err, res)=>{
 console.log(res);
})