skip to Main Content

The "tasks" field in the response is consistently empty, even though I know there are tasks associated with the user in the database.

I’ve checked my database records, and there are tasks assigned to the user in question, so the issue seems to be with how the data is being fetched or formatted in the API response.

I’ve double-checked my Mongoose models and ensured that the relationship between users and tasks is correctly defined and every response return tasks empty.

enter image description here

Auth midlleware

const verify = async (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (authHeader) {
    const token = authHeader.split(" ")[1];
    try {
      const decoded = await jwt.verify(token, process.env.JWT_ACCESS_KEY);
      req.user = decoded;
      next();
    } catch (err) {
      res.status(401).json({ message: err });
    }
  } else {
    res.status(403).json({ message: "Unauthorized" });
  }
};

GetAll controller tasks if user authorized:

const getAll = async (req , res) => {
  const userId = req.user.payload._id;
  if (userId) {
    try {
      const tasks = await userModel.findById(userId).populate("tasks");
      res.status(200).json({msg: "", data: tasks});
      console.log( req.user.payload.tasks);
      console.log( userId);
    } catch (err) {
      console.log(err);
    }
  } else {
    console.log(err);
  }
}

User schema:

const mongoose = require("mongoose");
const Schema =  mongoose.Schema;


const UserSchema = new Schema({
  name: {
    type: String,
  },
  email: {
    type: String,
    unique: true
  },
  password: {
    type: String,
  },
  tasks: [{ 
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'Task'
  }],
}) 

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

Task schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const TaskSchema = new Schema({
  title: {
    type: String,
  },
  status: {
    type: Boolean,
    default: false,
  },
  date: {
    type: String,
    default: new Date().toLocaleDateString().toString(),
  },
  owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
});

module.exports = mongoose.model("Task", TaskSchema);

Task in database

enter image description here

I tried every response return tasks field empty, As far as I understand relation between models in a good way.

enter image description here

2

Answers


  1. You code:

    const tasks = await userModel.findById(userId).populate("tasks");
    

    Try:

    const tasks = await userModel.findById(userId).populate(path:'tasks');
    

    Can you show an image of the saved user?

    Login or Signup to reply.
  2. you should store the tasks ids in the user entity as array so the populate work for you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search