node.js - 通过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 失败”}
解决方案
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 });
}
试试上面的
推荐阅读
- php - 如何从选项中获取输入,而我必须将数据输入到同一数据库的两个表中,基于选项数据将被插入
- php - 注意:未定义的偏移量:嵌套数组上的 0
- java - 如何在二维数组上使用比较器对用户输入进行排序
- roku - Roku 中的 roRegistrySection 问题?
- java - Kotlin 的主要构造函数的参数是完全私有的还是仅适用于 Java 代码?
- java - 在wiremock中使用ResponseTransformer总是得到空响应
- google-bigquery - 没有足够的资源用于查询计划
- python - 以通用方式比较 Excel 列并用一些颜色突出显示差异
- java - openhtmltopdf是否支持外部css
- java - 如何仅绘制传感器的当前数据点?