skip to Main Content

I have a nextjs application I have been developing and need to find all the documents in one of my collections I am using the mongodb node module. when i use .find() to pull the documents I just get an empty JSON object. I use .findOne, .updateOne with out any issues for my login and password reset pages. here is my code from the api.

     try{
      const client = await connectDatabase();
      const events = client.db().collection('members');
      const documents = events.find()
      res.status(200).json( documents);}catch(error){
      res.status(500).json({message: error.message});}

I have looked all over the mongodb documentation and have not found a solution to this issue.
this is what I get back when I run the code {"_events":{},"_eventsCount":0}

2

Answers


  1. MongoDB query is asynchronous, so you need to wait for the response. Change your code like this:

    const documents = await events.find();
    
    Login or Signup to reply.
  2. It’s because .find() returns a cursor so you can iterate it, the best you can do here is transform it into an array like below:

    const documents = await events.find().toArray();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search