首页 > 解决方案 > 通过node.js从mongodb获取数据

问题描述

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

我想通过“id”从我的 mongodb 获取数据。如果我的 id 与 mongodb 中的 id 值匹配,它将获取该对象,但它的抛出错误:

{“消息”:“模型“PostMessage”的路径“_id”的值“s-CoAhDKd”转换为 ObjectId 失败”}

标签: node.jsreactjsmongodbmongoosemongoose-schema

解决方案


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

试试上面的


推荐阅读