Search code examples
mongoosejwtmongoose-populate

Cannot populate author in blog post MERN stack using JWT


I am trying to create a blog site using MERN stack and JWT for authentication.

My User model is like this :

const mongoose = require("mongoose");
const { Schema } = mongoose;

const UserSchema = Schema({
  name: String,
  username: String,
  password: String,
  posts: [{ type: Schema.Types.ObjectId, ref: "Blog" }]
});

module.exports = mongoose.model("User", UserSchema);

My Blog model looks like:

const mongoose = require("mongoose");
const { Schema } = mongoose;

const BlogSchema = Schema({
  title: String,
  content: String,
  date: { type: Date, default: Date.now },
  author: { type: Schema.Types.ObjectId, ref: "Blog" }
});

module.exports = mongoose.model("Blog", BlogSchema);

I am using JWT to authenticate the Create new Blog Route. On logging in, I am sending a JWT token to the client with the current user's id and name as a payload. If the token sent from react front end is valid then I am adding the user's id to the req object while verifying the JWT. Ie. the req object will have a user_id field along with headers, body and others

The create new post route looks like this :

blog.post("/", authenticateUsingJwt, (req, res) => {
  // Validating the req.body object
  const newPost = new Blog({
    title: req.body.title,
    content: req.body.content,
    author: req.user_id
  });

  newPost.save();
});

When I am using my mongodb shell, and looking at my User collection, I see the posts[] to be an empty array. How to fix this so that I can use the populate?

User.findOne({ username: "existingUserInDatabase" })
  .populate("Blog")
  .then(user => res.send(user))
  .catch(err => console.log(err));

This code returns the User from the DB but the posts[] is an empty array.


Solution

  • You need to populate using blogs instead of Blog.

    User.findOne({ username: "existingUserInDatabase" })
      .populate("blogs")  //not "Blog"
      .then(user => res.send(user))
      .catch(err => console.log(err));