[英]Get my collection, req.query (express,node.js)
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 :我的 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] 由于更改而重新启动...
[nodemon] starting node ./bin/www
[nodemon] 起始node ./bin/www
(node:4279) DeprecationWarning: collection.ensureIndex is deprecated. (节点:4279)弃用警告:不推荐使用 collection.ensureIndex。 Use createIndexes instead.请改用 createIndexes。
(Use node --trace-deprecation ...
to show where the warning was created) (使用node --trace-deprecation ...
显示警告的创建位置)
undefined不明确的
GET /products 304 14.493 ms - - GET /products 304 14.493 毫秒 - -
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.您在 req.query上未定义,因为在服务器上请求时您尚未通过查询。 To pass query use ?id= In your Fetch File you should do following change:要传递查询使用?id=在您的提取文件中,您应该进行以下更改:
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')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.