I am getting below error
CastError: Cast to ObjectId failed for value "findByName" at path "_id" for model "Product" at new CastError (/Users/me/projects/nodejs/node_modules/mongoose/lib/error/cast.js:29:11) at ObjectId.cast (/Users/me/projects/nodejs/node_modules/mongoose/lib/schema/objectid.js:156:13)
API written in Nodejs
DB: mongoDB
Controller:
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
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?
Model:
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);
I am doing get call from postman:
URL: localhost:8080/products/findByName
Request Body:
{name: "name2"}