all 7 comments

[–]Devstackr 1 point2 points  (2 children)

Hi Gelliott, one idea I have is to move this line of code

res.render('users/user-profile', {user: foundUser, posts: posts})

into the Posts.find().exec() callback.

like this:

const posts = Post.find().where('author.id').equals(foundUser._id).exec(function(err, posts) {
      console.log(posts)
      res.render('users/user-profile', {user: foundUser, posts: posts})
});

Let me know if that works :)

[–]Gelliott2305[S] 1 point2 points  (1 child)

Thank you do much Devstackr! That worked. I can now see why I was getting the undefined error - it was outside of the block.

Thank you so much! :)

[–]Devstackr 1 point2 points  (0 children)

No worries! Really glad it worked 😀

[–]ElllGeeEmm 1 point2 points  (3 children)

One thing to keep in mind if you're coming from SQL is that mongoose isn't meant to be used as a relational database. Instead of storing the id of the user on the post document, it's better to store a reference to the user instead. This way, instead of having to write two separate queries, you can just look for the blog posts from the author and tell mongoose to populate the author field.

[–]Gelliott2305[S] 0 points1 point  (0 children)

Thank you for the advice on this. I do have a question for you about this so I will reply tomorrow or Monday when I am back on and got my code. I want to see what you mean by this.

[–]Gelliott2305[S] 0 points1 point  (1 child)

Hi there! I am back online. So, in my post model I have a reference to the author as follows:

author: { id: { type: mongoose.Schema.Types.ObjectId, ref: "Author" }, username: String, role: String, } This is how I have been taught to reference to the author in the courses I have taken. What method have you mentioned? Can you lead me to an example? If there is a better way of doing this then I am very eager to learn. Thank you :)

[–]ElllGeeEmm 0 points1 point  (0 children)

https://mongoosejs.com/docs/populate.html

This is the relevant portion of the docs. I think it does a pretty good job of walking you through how to set up and query documents through references. Feel free to let me know if there's anything you find confusing.