get data from mongodb through node.js

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""}

Upvotes: 0

Views: 83

Answers (2)

Vijay Gangatharan
Vijay Gangatharan

Reputation: 298

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

Upvotes: 1

Kilian P.
Kilian P.

Reputation: 660

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 ;)

Upvotes: 1

Related Questions