将 url id 从 react-router 传递给 mongoose
Passing url id from react-router to mongoose
我正在尝试学习 MERN 堆栈,这是一个简单的愚蠢问题,我已经好几天没弄明白了。
我正在尝试使用 express 和 mongoose 作为后端向 api 发出 GET 请求,并在前端做出反应,反应路由器。
这是 api 请求:
router.get('/:id', (req, res) => {
Product.findById(req.params.id)
.then(product => res.json(product))
});
我把路由设置成这样:
<Route path="/:id" component={Product}></Route>
这是我使用 axios 执行 GET 请求的产品组件:
componentWillMount() {
axios.get("/api/products/:id")
.then(res => this.setState({
product: res.data
}))
.catch(err => console.log(err))
}
它给出了错误:
CastError: Cast to ObjectId failed for value ":id" at path "_id" for model "product"
我已经找了好几天了,但仍然没有找到解决这个问题的方法,我认为这与 mongoose scheema 的自动 id 是 _id
有关,这导致了一些问题api。
架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema; // Create Schema
const ProductSchema = new Schema({
name: {
type: String,
required: true,
},
pic: {
type: String,
},
price: {
type: Number,
},
sale: {
type: Number,
}
});
module.exports = Product = mongoose.model('product', ProductSchema);
提前谢谢大家!
请检查您的 req.params.id
的有效性,作为 mongo 查询的有效 ID。错误是关于 id 不是实际的 objectId mongo 可以使用。
我在几个小时后解决了这个问题 google,结果是当我点击 link 时,它指向 products/:id
而不是实际的 id,我必须做的是 const link = '/products/' + this.props.product._id
并在 <a>
标签中传递 link
。
我正在尝试学习 MERN 堆栈,这是一个简单的愚蠢问题,我已经好几天没弄明白了。 我正在尝试使用 express 和 mongoose 作为后端向 api 发出 GET 请求,并在前端做出反应,反应路由器。 这是 api 请求:
router.get('/:id', (req, res) => {
Product.findById(req.params.id)
.then(product => res.json(product))
});
我把路由设置成这样:
<Route path="/:id" component={Product}></Route>
这是我使用 axios 执行 GET 请求的产品组件:
componentWillMount() {
axios.get("/api/products/:id")
.then(res => this.setState({
product: res.data
}))
.catch(err => console.log(err))
}
它给出了错误:
CastError: Cast to ObjectId failed for value ":id" at path "_id" for model "product"
我已经找了好几天了,但仍然没有找到解决这个问题的方法,我认为这与 mongoose scheema 的自动 id 是 _id
有关,这导致了一些问题api。
架构:
const mongoose = require('mongoose');
const Schema = mongoose.Schema; // Create Schema
const ProductSchema = new Schema({
name: {
type: String,
required: true,
},
pic: {
type: String,
},
price: {
type: Number,
},
sale: {
type: Number,
}
});
module.exports = Product = mongoose.model('product', ProductSchema);
提前谢谢大家!
请检查您的 req.params.id
的有效性,作为 mongo 查询的有效 ID。错误是关于 id 不是实际的 objectId mongo 可以使用。
我在几个小时后解决了这个问题 google,结果是当我点击 link 时,它指向 products/:id
而不是实际的 id,我必须做的是 const link = '/products/' + this.props.product._id
并在 <a>
标签中传递 link
。