【发布时间】:2019-01-24 02:02:35
【问题描述】:
我正在尝试学习 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 请求的 Product 组件:
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);
提前谢谢大家!
【问题讨论】:
-
你能发布产品的架构/模型吗?
-
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); -
id是mongoose自动生成的
标签: express mongoose react-router mern