Warm tip: This article is reproduced from stackoverflow.com, please click
express node.js

What causes this "Cast to ObjectId" error in a Express.js application?

发布于 2020-03-28 23:14:08

I am working on a blogging application with Express, EJS and MongoDB.

In my posts.js controller I have:

exports.addPostForm = (req, res, next) => {
    res.render('addpost', {
        website_name: 'MEAN Blog',
        page_heading: 'Add New Post'
    });
};

The form in the addpost view:

<form method="post" action="postadded" name="sentMessage" class="w-100" novalidate>
    <div class="control-group">
        <div class="form-group floating-label-form-group controls">
            <label>Post title</label>
            <input type="text" class="form-control" placeholder="Post title" name="title" id="title" required>
            <p class="help-block text-danger"></p>
        </div>
    </div>
    <div class="control-group">
        <div class="form-group floating-label-form-group controls">
            <label>Post summary</label>
            <input type="email" class="form-control" placeholder="Post summary" name="summary" id="summary" required>
            <p class="help-block text-danger"></p>
        </div>
    </div>

    <div class="control-group">
        <div class="form-group floating-label-form-group controls">
            <label>Post content</label>
            <textarea rows="5" class="form-control" placeholder="Post content" name="full_text" id="fullText" required></textarea>
            <p class="help-block text-danger"></p>
        </div>
    </div>
    <div class="form-group mt-4">
        <button type="submit" class="btn btn-primary" id="addPostButton">Add Post</button>
    </div>
</form>

It the routes I have:

router.get('/addpost', postsController.addPostForm);

Finally, the model:

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    short_description: {
        type: String,
        required: true
    },
    full_text: {
        type: String,
        required: true
    }
});

module.exports = mongoose.model('Post', postSchema);

I thought nothing was missing an yet I get this error in the console:

'Cast to ObjectId failed for value "addpost" at path "_id" for model "Post"'

What is missing?

Questioner
Razvan Zamfir
Viewed
52
Abanoub Istfanous 2020-02-05 11:35

The error caused because there are function with :id param and handled with controller which gets an object like that

router.get('/:id', postsController.controllerFunction);

and the /addpost trait as a param not a path try to change the order of the routes