温馨提示:本文翻译自stackoverflow.com,查看原文请点击:node.js - What causes this "Cast to ObjectId" error in a Express.js application?

node.js - 是什么导致Express.js应用程序中出现“对象转换为ObjectId”错误?

发布于 2020-03-28 23:23:49

我正在使用ExpressEJS和MongoDB开发博客应用程序

在我的posts.js控制器中,我有:

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

addpost视图中的表单

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

它是我的路线:

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

最后,模型:

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);

我以为一切都没有丢失,但是我在控制台中收到此错误:

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

缺什么?

查看更多

查看更多

提问者
Razvan Zamfir
被浏览
44
Abanoub Istfanous 2020-02-05 11:35

由于存在具有:id参数的函数并由获取了类似对象的控制器处理而导致的错误

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

和/ addpost特性作为参数而不是路径,尝试更改路由的顺序

发布
问题

分享
好友

手机
浏览

扫码手机浏览