0
const postSchema = mongoose.Schema({
  id: String,
  name: String,
  isbn: String,
  image: String,
})

var PostMessage = mongoose.model('PostMessage', postSchema);


const getBook = async (req, res) => { 
  const { id } = req.params;

  try {
      const post = await PostMessage.findById(id);
      
      res.status(200).json(post);
  } catch (error) {
      res.status(404).json({ message: error.message });
  }
}

i want to get data from my mongodb through "id" . if my id matches the value of id in mongodb it gets that object,but its throwing error:

{"message":"Cast to ObjectId failed for value "s-CoAhDKd" at path "_id" for model "PostMessage""}

2 Answers2

1

Based on this thread : What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

You have to check if your ID meets the requirements of Mongoose ObjectId structure with :

mongoose.Types.ObjectId.isValid('your id here');

In the docs : https://mongoosejs.com/docs/schematypes.html#objectids, it indicates that ObjectIDs are 24 characters hash. So "s-CoAhDKd" is not a correct format ;)

Kilian P.
  • 650
  • 1
  • 5
  • 9
1
const { id } = req.params;

try {
    const post = await PostMessage.findById({id: id});
    res.status(200).json(post);
} catch (error) {
  res.status(404).json({ message: error.message });
}

Try the above

Vijay
  • 228
  • 3
  • 8