Reputation: 23
When trying to log the data from DB using findById
I get a return value of undefined
.
// Get single article
app.get('/article/:id', (req, res) => {
Article.findById(req.params.id, (err, article) => {
console.log(article);
return;
});
});
//Article Schema
let articleSchema = mongoose.Schema({
title: { type: String, required: true },
author: { type: String, required: true},
body: { type: String, required: true}
});
let Article = module.exports = mongoose.model('Article', articleSchema)
i looked up a few things and i got it to work but im not sure if that is the correct way to do it
so what i found was that if i use findOne()
and pass in Article.id
i get the result i want, but is that the correct way of doing things?
i feel like the article.id
should be passed by the req.params.id
, but when i pass that into findOne()
i get an error saying:
Error: Invalid argument to findOne(): 'article_id'
Upvotes: 2
Views: 2963
Reputation: 1
Are you pulling in the correct ID from your database, on your link that sends you to /article/:id. I had the same problem, as I previously learned on basic array indexes and moved to MongoDB. I just needed to update one character to include the underscore for the MongoDB syntax of '_id' as opposed to 'id'.
The correct code that worked for me on my HTML rendered pages had the below:
<a href={`/article/${article._id}`}>
What I started with and gave me an undefined result was the below:
<a href={`/article/${article.id}`}>
Upvotes: 0
Reputation: 570
Use Article.findById(mongoose.Types.ObjectId(req.params.id)}, (err, article)...
As you are looking for object id and not a String.
Upvotes: 1