Skip to content

collection.find({}) doesnt work after many tries

I am building an api with express and mongoose and im usingdb.collection(collection).find({}) expecting that i get all of my docs back (3 test docs in total) as seen from tutorials. It doesnt give me any errors when im executing a req from postman and that confuses me as im geting nothing, not even an empty object or array as a response. I have tried different examples, from different tutorials but nothing works. Is the syntax wrong?

import express from 'express'
import './connection.js'
const router = express.Router
const db = mongoose.connection;
const dtb = db.useDb('main').collection('products')

router.get('/true', async(req, res) => {
    try {
            const products = await dtb.find({})
            res.send(products).status(200)
        

    } catch (err) {
        console.log(err)
        res.sendStatus(500)
    }
})

Answer

So, after lookig again and again at my code I realized that the route /true was taken as a param by express as i have another route for app.get('/:_id', getItem). After changing the route to /all/true parsing the docs into an array and after some debugging, my getAll function looks like this and finally works :

export const getAll = app.get('/all/true', async(req, res) => {

    const products = await dtb.find({}).toArray().catch(console.error())

    res.send(products)


})