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)
CodePudding user response:
I see two issues with your code:
Are you sure it should be:
db.db.collection
and notdb.collection
? Hard to tell without seeing your DB init code, but just double check that first.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();