【问题标题】:mongoose Argument passed in must be a single String of 12 bytes or a string of 24 hex charactersmongoose 传入的参数必须是 12 字节的单个字符串或 24 个十六进制字符的字符串
【发布时间】:2020-11-12 23:58:16
【问题描述】:

我不明白为什么会出现这个问题:

CastError: Cast to ObjectId failed for value "5fa41e7f4ee57a30687e80e9 " at path "_id" for model "page"
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters,

这段代码之后

router.post('/edit-page/:slog', (req, res) => {

    req.checkBody('title', 'Le champs titre doit être remplis').notEmpty()
    req.checkBody('content', 'Le champs content doit être remplis').notEmpty();
    let title = req.body.title
    let slog = req.body.slog.replace(/\x+/g, '-').toLowerCase();
    if (slog == "") slog = title.replace(/\x+/g, '-').toLowerCase();
    let content = req.body.content
    let id = req.body.id

    const errors = req.validationErrors();
    if (errors) {
        res.render('admin/edit_page', {
            errors: errors,
            title: title,
            slog: slog,
            content: content,
            id: id
        })
    } else {
        Page.findOne({ slog: slog, _id: { "$ne": id } }, (err, page) => {
            if (page) {
                req.flash('danger', 'Cette page existe, choisis une autre!');
                res.render('admin/edit_page', {
                    title: title,
                    slog: slog,
                    content: content,
                    id: id
                });
            } else {
                Page.findById(id, function (err, page) {
                    console.log(id)
                    if (err)
                        console.log(err)

                    page.title = title;
                    page.slog = slog;
                    page.content = content;

                    page.save(function (err) {
                        if (err) {
                            console.log(err)
                        } else {
                            req.flash('success', 'page sauvegardée')
                            res.redirect('/admin/pages')
                        }
                    })

                })

            }

        })
    }
})

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    您的字符串存在最小错误。最后有一个空格。

    字符串5fa41e7f4ee57a30687e80e9 应该是5fa41e7f4ee57a30687e80e9

    使用猫鼬我已经检查过并且可以工作:

    var id = mongoose.Types.ObjectId("5fa41e7f4ee57a30687e80e9");
    

    我还解释了ObjectId 在这个question 中的工作原理,如果你想检查的话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多