E
E
embiid2019-12-19 12:03:13
MongoDB
embiid, 2019-12-19 12:03:13

How to avoid CastError?

I came across such a problem with the work of nodejs and mongo.
I am making such a crm system where you can edit and delete entries.
Everything is fine with editing, but it does not work with records that should be deleted.
It gives an error like: "CastError: Cast to ObjectId failed for value "5dd050dd54b4a11fe4e2724adelete" at path "_id" for model "Post"
" , tried but nothing worked, npm gave me an error and prompted the npm audit / + fix command, which updated mongodb || mongoose.
Even if you leave mongoose on version 4, the terminal writes that one of the functions, either remove / delete, is outdated, and you must use deleteOne || removeOne.

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const PostSchema = new Schema({
    title: {
        type: String,
        required: true
    },

    status: {
        type: String,
        default: 'public'
    },

    allowComments: {
        type: String,
        required: true
    },

    body: {
        type: String,
        require: true
    },
})

module.exports = mongoose.model('Post', PostSchema)

Route code:
router.delete('/:id', (request, response) => {
    Post.remove({ _id: request.params.id}).then(result => {
            response.redirect('/admin/posts')
    })
})

Hope for your advice)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-12-19
@embiid

value "5dd050dd54b4a11fe4e2724a delete "
looks like this extra delete is added to the ID already in req.params.id?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question