简体   繁体   English

如何从MongoDB获取文档?

[英]How to get documents from MongoDB?

I have a database on MongoDB Atlas. 我在MongoDB Atlas上有一个数据库。 Using NodeJS I established a connection and tried to get some data. 使用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"})
    });

When I tried console.log(collection) I got big object as output (I guess it's what's called a cursor) 当我尝试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 ....

When I tried collection.forEach(member => console.log(member)) I got an error TypeError: collection.forEach is not a function . 当我尝试collection.forEach(member => console.log(member)) ,出现错误TypeError: collection.forEach is not a function My question is, how can get my data from the database? 我的问题是,如何从数据库中获取数据?

You are missing the step to "find" all the documents. 您缺少“查找”所有文档的步骤。

ex from w3schools : 来自w3schools:

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

I recommend to use mongoose, it's a lot simpler. 我建议使用猫鼬,这要简单得多。

But the actual code is 但是实际的代码是

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

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

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

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