skip to Main Content

Hi i am new to mongodb and i have this error coming when i am hitting this endpoint localhost:3000/api/v1/tours/1

Error message

{
    "status": "failure",
    "message": "Cast to ObjectId failed for value "1" (type string) at path "_id" for model "Tour""
}

Error image

exports.getTour = async (req, res) => {
  try {
    const tour = await Tour.findById(req.params.id);
    res.status(200).json({
      status: 'success',
      data: {
        tour
      }
    });
  } catch (err) {
    res.status(404).json({
      status: 'failure',
      message: err.message
    });
  }
};

this is the function which is supposed to give me the tour data with the specific id.

i am attaching the schema here

const mongoose = require('mongoose');

const tourSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'A tour must have a name'],
    unique: true
  },
  rating: {
    type: Number,
    default: 4.5
  },
  price: {
    type: Number,
    required: [true, 'A tour must have a price']
  }
});

const Tour = mongoose.model('Tour', tourSchema);

Here is the data present in atlas database
mongoose data

2

Answers


  1. When you issue a GET request to:

    localhost:3000/api/v1/tours/1
    

    Your code is grabbing req.params.id which is 1. Since you are using that as a parameter to findById() mongoose is trying to cast 1 to an ObjectId for you so that it can find the document. Well firstly, 1 isn’t castable to an ObjectId and secondly, you don’t have a document with an _id === 1.

    I think the route you need to request is:

    localhost:3000/api/v1/tours/65756e8badeb705e687e7aa9
    
    Login or Signup to reply.
  2. I can see that from this image that 65756e8badeb705e68Te7aa9 this is your data ID for created Tour data.

    MongoDb use uuid to create 12-byte random id So you have to pass 65756e8badeb705e68Te7aa9 as id to get data from mongoDb collection.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search