I’m running into an error when I try to GET one of my routes.
Here is my Item model:
models/item.js
const { Schema, model } = require('mongoose');
const ItemSchema = new Schema({
name: {
type: String,
required: true,
minLength: 1,
maxLength: 50,
},
description: {
type: String,
maxLength: 200,
},
category: {
type: Schema.Types.ObjectId,
ref: 'Category',
required: true,
},
price: {
type: Schema.Types.Decimal128,
required: true,
},
stock: {
type: Number,
required: true,
},
url: {
type: String,
required: true,
minLength: 1,
}
});
ItemSchema.virtual('appUrl').get(function () {
return `/item/${this._id}`;
});
module.exports = model('Item', ItemSchema);
Here is my item controller:
itemContoller.js
// renders create item page on GET
exports.item_create_get = function (req, res, next) {
Category.find({}).then((result) => {
if (err) {
return next(err);
}
res.render('item_create_get', { title: 'Create Item', categories: result });
});
}
The route is:
routes/index.js
// GET create item
router.get('/item/create', itemController.item_create_get);
And the error I’m receiving is:
UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "create" (type string) at path "_id" for model "Item"
I think it may have something to do with the model the category is referencing, so here is that model:
models/category.js
const { Schema, model } = require('mongoose');
const CategorySchema = new Schema({
name: {
type: String,
required: true,
minLength: 1,
maxLength: 25,
},
description: {
type: String,
maxLength: 50,
},
});
CategorySchema.virtual('appUrl').get(function () {
return `/category/${this._id}`;
});
module.exports = model('Category', CategorySchema);
>Solution :
This is happening because of the way your routes are structured. Mongoose is trying to cast the value "create" to an ObjectId, which is not possible. You need to reorder your routes.
router.get('/item/create', itemController.item_get); // you need to make sure this route handler comes first
router.get('/item/:id', controller_to_fetch_item_by_id);
But I am not sure what you are trying to ‘get’ with a ‘create’ route anyway. It should be a ‘post’ to begin with. Then you won’t have to reorder your routes.