• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

488
Views
How to select * from 'x' in mongodb?

I'm trying to receive all fields in my database in my API call

My code:

exports.objfields = async (req, res, next) => {
  try {
    var db = mongo.connection;  
    var objeto = req.headers.objeto;
    const result = db.db.collection(objeto).find();
    return res.status(200).send({message:result});
  } catch (error) {
    return res.status(401).send({ message: error.message });
  }
};

For results 200 it's returning me the following sentence "message": {"_events": {},"_eventsCount": 0} , how can I return the fields in the API call? (obs. I also tried find({}), but it returns the same thing)

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I see two issues with your code:

  1. Are you sure it should be: db.db.collection and not db.collection ? Hard to tell without seeing your DB init code, but just double check that first.

  2. You need to use async/await to wait for MongoDB to return the result to your Node application:

const result = await db.collection(objeto).find();

find() returns a JS Promise, not a direct value immediately. For more details on async/await, you can check:

https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await

If you end up with a Cursor object but cannot see the values, try to convert the Cursor into an array using toArray():

For example:

const cursor = collection.find({});
const allValues = await cursor.toArray();

https://docs.mongodb.com/drivers/node/current/fundamentals/crud/read-operations/cursor/#return-an-array-of-all-documents

about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error