1

i use Mongoose to get my data from my database with this get function.

router.get("/:id", async (req, res)=> {
  const products = await Product.findOne({slug: req.params.id});
  if (products) {
    res.send(products);
  } else {
    res.status(404).send({message:"product not found"})
  } 
});

The output seems to be an object. However i need a array instead, because i use the slice() method in my further code.

What i tried: var ready = Object.keys(products).map((key) => [Number(key), products[key]]);

Is there any function i could use to make an array instead of the object or another mongoose function for getting an array?

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

lel theres always a simple approach.. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.