Emil Østervig
Emil Østervig

Reputation: 460

how to properly cast ObjectId in mongoose

I'm running into some issues with casting ObjectId in express.js using mongoose.

In my route i have tried both casting before as well as just using the req.params.id directly. Nothing seems to work. I'm 100% certain the id is correct. I have tried creating a new post and directly copying the id multiple times.

Any ideas why my ObjectId is not recognized?

My Schema:

let PostSchema = new Schema({
    _id: {type: mongoose.Schema.Types.ObjectId, auto: true},
    title: String,
    author: String,
    date: { type: Date, default: Date.now()},
    body: String,
    comments: [CommentSchema],
    upvotes: Number,
    downvotes: Number, 
});

My route:

app.post('/api/post/:id/comment', (req, res) => {
    let comment = new PostComment({
        author: req.body.author,
        body: req.body.body,
        date: req.body.date,
        upvotes: 0,
        downvotes: 0,
    })
    const id = mongoose.ObjectId.cast(req.params.id)
    Post.findOneAndUpdate(
        {_id: id},
        { $push: {comments: comment}}
        )
        .then(result => {
            if(!result) {
                res.sendStatus(404).send({
                    success: 'false',
                    message: 'Comment not added',
                });
            } else {
                res.status(200).json(result);
            }
        })
        .catch(err => console.log(err));
});

The Error message:

Cast to ObjectId failed for value "{ id: \'5cc3632db9e2405960e3ed0e\' }" at path "_id" for model "Post"

Extra route with same issue:

// get single post by id
app.get("/api/post/:id", (req, res) => {
    const id = req.params;
    Post.findById(id)
        .exec()
        .then(result => {
            if(!result) {
                res.sendStatus(404).send({
                    success: 'false',
                    message: 'No post found',
                });
            } else {
                res.status(200).json(result);
            }
        })
        .catch(err => console.log(err));

});

Upvotes: 1

Views: 2606

Answers (1)

Emil Østervig
Emil Østervig

Reputation: 460

It seems as soon as you post on SO you will find the answer yourself, so here goes. This function will effectively cast a string to an ObjectId: mongoose.Types.ObjectId(req.params.id);

Upvotes: 3

Related Questions