Search code examples
node.jsmongoose

Populate method is not working as expected


I have 2 schemas project and task.

const mongoose = require("mongoose"); 
const projectSchema = new mongoose.Schema({
  title: String,
  sub_title: String,
  tasks: [{ type: mongoose.Schema.Types.ObjectId, ref: "Task" }],
});

const Project = mongoose.model("Project", projectSchema);

module.exports = Project;
const mongoose = require("mongoose"); 
const taskSchema = new mongoose.Schema({
  title: String,
  sub_title: String,
  time: String,
  projectId: String,
  timeSheet:[],
  project: { type: mongoose.Schema.Types.ObjectId, ref: "Project" },
});

const Task = mongoose.model("Task", taskSchema);

module.exports = Task;

I let the user enter the project details and then can add the tasks in it. I used populate method to get the all tasks related to a specific project inside of project schema . But when I get all projects it is not adding tasks in it. Please help me with this bug.

I have tried to add tasks by pushing it but when I update the task it is not showing in projects schema


Solution

  • Unfortunately, mongoose relations are not established automatically and therefore you will still need to add the Project _id into each Task. Just like you have added each Task _id into the project array of each Project.

    //Get the id of the Project and Task that are related
    const projectid = req.body.projectid;
    const taskid = req.body.taskid;
    
    // Get the Parent Project. I have used findById() for demonstration 
    const project = await Project.findById(projectid);
    
    // Add the project._id ObjectId into the task.project field. 
    // I have used findByIdAndUpdate() for demonstration 
    const task = await Task.findByIdAndUpdate(taskid,
       { project: project._id },
       { new: true }
    );
    
    // Add the task._id ObjectId into the project.tasks array.  
    project.tasks.push(task._id);
    await project.save();
    

    Now when you want to get the Projects and call populate it will lookup the Tasks and replace the ObjectId with the full document in each Project.