简体   繁体   中英

How to get documents from MongoDB?

I have a database on MongoDB Atlas. Using NodeJS I established a connection and tried to get some data.

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)

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 . My question is, how can get my data from the database?

You are missing the step to "find" all the documents.

ex from 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);
})

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