无法在我的数据库中找到记录,尽管它存在于我的数据库中
unable to find a record in my db although it is present in my db
我正在使用 findOne() 方法通过以下代码搜索我的数据库
app.get("/articles/:articleId", (req, res) => {
Article.findOne({ _id: req.params.articleId}, (err, foundArticle) => {
if(foundArticle) {
res.send(foundArticle);
} else {
res.send("No article found");
}
});
});
在 postman
中使用以下 URL
http://localhost:3000/articles/626e950e4fb74295f5139b78
并为数据库中的以下记录传递 object id
{
"_id": "626e950e4fb74295f5139b78",
"title": "Albert Einstein",
"content": "Did you know that sleep is good for your brain? Einstein sure did, he slept for 10 hours a day!",
"__v": 0
}
但是我找到一个代码 returns 没有找到文章,即使文章存在
collection模态
const articleSchema = {
title: String,
content: String
};
const Article = mongoose.model("Article", articleSchema);
在尝试了不同的解决方案后,我终于通过以下方式解决了问题
在架构中添加 _id: 字符串可解决问题
const articleSchema = {
_id: String,
title: String,
content: String
};
其余代码将保持不变
我正在使用 findOne() 方法通过以下代码搜索我的数据库
app.get("/articles/:articleId", (req, res) => {
Article.findOne({ _id: req.params.articleId}, (err, foundArticle) => {
if(foundArticle) {
res.send(foundArticle);
} else {
res.send("No article found");
}
});
});
在 postman
中使用以下 URLhttp://localhost:3000/articles/626e950e4fb74295f5139b78
并为数据库中的以下记录传递 object id
{
"_id": "626e950e4fb74295f5139b78",
"title": "Albert Einstein",
"content": "Did you know that sleep is good for your brain? Einstein sure did, he slept for 10 hours a day!",
"__v": 0
}
但是我找到一个代码 returns 没有找到文章,即使文章存在
collection模态
const articleSchema = {
title: String,
content: String
};
const Article = mongoose.model("Article", articleSchema);
在尝试了不同的解决方案后,我终于通过以下方式解决了问题 在架构中添加 _id: 字符串可解决问题
const articleSchema = {
_id: String,
title: String,
content: String
};
其余代码将保持不变