I want to recover my collection which is in the database. The problem is that my query is still not defined.
Here is my request:
const products = {
getProducts: async (req, res) => {
const productId = req.query.id;
console.log(productId);
const product = await ProductsModel.find({}).exec();
if (product instanceof Error) {
res.status(500).json({ message: "Error" });
return;
}
res.json(product);
},
};
module.exports = products;
My schema with mongoose :
const ProductSchema = new mongoose.Schema({
image: {
type: String,
},
title: {
type: String,
},
description: {
type: String,
},
price: {
type: Number,
},
category: {
type: String,
},
});
const Products = mongoose.model("Products", ProductSchema);
module.exports = Products;
My Fetch :
const [products, setProducts] = useState([]);
useEffect(getProducts, []);
async function getProducts() {
const options = {
method: "GET",
}
const response = await fetch("http://localhost:8000/products", options);
const productsData = await response.json();
setProducts(productsData);
console.log(productsData);
}
My error message :
[nodemon] restarting due to changes...
[nodemon] starting node ./bin/www
(node:4279) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
(Use node --trace-deprecation ...
to show where the warning was created)
undefined
GET /products 304 14.493 ms - -
Thank you in advance for your help.
At first, while exporting from your Schema file you have done:
module.exports = Products;
But on your Request file while fetching product you have done:
const product = await ProductsModel.find({}).exec();
You should replaced it with:
const product = await Products.find({}).exec();
You are getting undefined on req.query because while request on server you have not passed query. To pass query use ?id= In your Fetch File you should do following change:
const response = await fetch("http://localhost:8000/products?id="+productId, options);
Or, You can also use Tempelate Literals `` , this is a good practice.
const response = await fetch(`http://localhost:8000/products?id=${productId}`, options);
For deprecation warning, you have to do following changes where you have connect databse.
mongoose.connect('mongodb://localhost:27017/name',{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex:true},()=>{console.log('database connected')}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.