即使数据库中存在findById()
,以下null
也会返回id
:
router.get('/product/:id', function (req, res) {
console.log("product id = " + req.params.id);
//produces product id = 596161e1734d1d25634366ce
var id = req.params.id;
Product.findById({_id: req.params.id})
.exec(function (err, product) {
if (err) {
console.error('Error retrieving all product by id!');
} else {
console.log('server product = ' + JSON.stringify(product));
res.json(product);
}
})
})
数据库中的目标文档:
{
"_id": {
"$oid": "596161e1734d1d25634366ce"
},
"producttype": "stove",
"name": "30 in. 4.8 cu. ft. Electric Range in Stainless Steel",
"brand": "Amana",
"model": "AER6303MFS",
}
型号:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
_id: String,
productType: String,
name: String,
brand: String,
model: String,
price: Number,
discount: Number,
description: String,
rating: Number,
sku: String,
warranty: String,
});
var Product = mongoose.model('Product', ProductSchema, 'product');
module.exports=Product;
答案 0 :(得分:1)
取自docs,您是否尝试仅传递req.params.id
而不是对象?像这样:
Product.findById(req.params.id)
.exec(function (err, product) {
if (err) {
console.error('Error retrieving all product by id!');
} else {
console.log('server product = ' + JSON.stringify(product));
res.json(product);
}
})
})
答案 1 :(得分:1)
尝试从ProductSchema中删除_id。 Id将由mongodb自动生成。之后尝试使用
Product.find({_id: req.params.id})
.exec(function (err, product) {
if (err) {
console.error('Error retrieving all product by id!');
} else {
console.log('server product = ' + JSON.stringify(product));
res.json(product);
}
})
})
或者如果您想使用find by id,请使用
Product.findById(req.params.id)
.exec(function (err, product) {
if (err) {
console.error('Error retrieving all product by id!');
} else {
console.log('server product = ' + JSON.stringify(product));
res.json(product);
}
})
})