CastError:对路径处的值“findByName”转换为ObjectId失败
在新的CastError(/Users/me/projects/nodejs/node_modules/mongoose/lib/error/cast.js:29:11)
在ObjectId.cast(/Users/me/projects/nodejs/node_modules/mongoose/lib/schema/ObjectId.js:156:13)
DB:mongoDB
控制器:
exports.product_details_by_name = function (req, res) {
Product.findByProductName(req.params.name, function (err, product) {
if (err){console.log(err); return next(err);}
res.send(product);
})
};
路由器
router.get('/test', product_controller.test);
router.post('/create', product_controller.product_create);
router.get('/:id', product_controller.product_details);
router.put('/:id/update', product_controller.product_update);
router.delete('/:id/delete', product_controller.product_delete);
router.get('/findByName', product_controller.product_details_by_name); // two get methods?
型号:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let ProductSchema = new Schema({
name: {type: String, required: true, max: 100},
price: {type: Number, required: true},
});
ProductSchema.findByProductName = function(nam) { // is it right to do?
console.log("name"+nam);
return this.find({ "name": nam });
};
// Export the model
module.exports = mongoose.model('Product', ProductSchema);
网址:
localhost:8080/products/findByName
{name: "name2"}