Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Express UnhandledPromiseRejectionWarning: CastError

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading