findOne() 不起作用:
app.get('/api/products/:id', (req, res, next) => {
console.log('Product.findOne({ id:'+req.params.id+'}) :' );
Product.findOne({ _id: req.params.id })
.then(product => { console.log("\nprod =\n"+json({product})); res.status(200).json({product})} )
.catch(error => { console.log('error here'); res.status(404).json({ error })} );
});
我的后端服务器在终端中显示: enter image description here
另外两条路线正常工作: enter image description here
这些项目确实在数据库中: enter image description here
我尝试用 FindById() 替换 findOne()。 我是初学者,一直在努力寻找解决方案,但无济于事。
答案 0 :(得分:0)
问题
您正在尝试将字符串与 ObjectId 进行比较
解决方案
https://docs.mongodb.com/manual/reference/method/ObjectId/
const ObjectId = require('mongodb').ObjectId;
const id = ObjectId(req.params.id); // convert to ObjectId
Product.findOne({ _id: id })
答案 1 :(得分:0)
你可以做这样的事情来让它工作。
app.get('/api/products/:id', (req, res, next) => {
Product.findOne({_id: req.params.id })
.then(product => {
console.log(product) //To check the value we got from query
res.status(200).json({product})
})
.catch(err => {
console.log(err)
})
});