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""
}
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
When you issue a
GET
request to:Your code is grabbing
req.params.id
which is1
. Since you are using that as a parameter tofindById()
mongoose is trying to cast1
to anObjectId
for you so that it can find the document. Well firstly,1
isn’t castable to anObjectId
and secondly, you don’t have a document with an_id === 1
.I think the route you need to request is:
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 pass65756e8badeb705e68Te7aa9
as id to get data from mongoDb collection.