How do i get an array instead of an object using mongoose?
The easier approach would be to use find
as it always returns an array. In your case:
const products = await Product.findslug: req.params.id});
Also note that if (products) {
would now always return true
, so you may want to update to if (products.length) {
(in case you need at least 1 document).
There's also aggregate
method available that also returns an array but usually it's being used for a little more advanced queries. If your query is as simple as you have provided, you don't need aggregate
here.