Search code examples
node.jsreactjsmongodbmongoosemongoose-schema

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


Solution

  • 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