SakoBu SakoBu - 12 days ago 5
Node.js Question

Getting all Posts that belong to one User and display to pass to the view Node / Express / Mongoose

Below is the code for User model, Post model and the route. I need to query the DB and then pass to the view through the router. What am I missing?

User model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});

module.exports = mongoose.model('User', userSchema);


Posts model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var postSchema = new Schema({
postTitle: {
type: String,
required: true
},
postStory: {
type: String
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
});

module.exports = mongoose.model('Post', postSchema);


And here is the query in the router that I'm trying but apparently it's not the way to go...

My GET route:

router.get('/dashboard', isLoggedIn, function(req, res) {
Post.find({author:req.user._id}, (err, posts) => {
if(err) {
console.log(err);
} else {
res.render('users/dashboard', {currentUser: req.user, posts: posts});
}
});
});


What am I missing here?

Answer

You may want to change the find query to match the proper attribute in the following line:

Post.find({author: req.user._id}, (err, posts) => {

to be:

Post.find({'author.id': req.user._id}, (err, posts) => {

Read more: http://mongoosejs.com/docs/2.7.x/docs/finding-documents.html

Comments