I want to return all data in MongoDB, it returns 200, but I cannot get all the data properly.
I am using Express
I am learning to use MongoDB and doing homework for practice. The task just told me to set up the API for MongoDB, they gave me an HTML with a button to test the API, and the HTML will show the API success or not, I cannot check on the HTML.
The task that I fail is told me to get all data from MongoDB.
Here is the task which I fail
GET
/api/products. Returns all products in the database as{ products: Product[] }
I success to post data to MongoDB, when I use 'app.get()' to get all my data from MongoDB it fail, but I got 200 for the return, and I can see some data in the log.
That is the app.get() that I write
app.get('/api/products', (req, res, next) => {
Product.find().then(
(product) => {
res.status(200).json({product});
}
).catch(
(error) => {
res.status(404).json({
error: error
});
}
);
});
The below code seems to work fine for me. Please check it out.
app.get('/api/products', (req, res, next) => {
Product.find({})
.exec()
.then(
(product) => {
res.status(200).json({product});
}
).catch(
(error) => {
res.status(404).json({
error: error
});
}
);
});