Search code examples
node.jsdatabasemongodbnodesmongoose-populate

Mongoose: Saving ref of another document into an array of objects document returns empty array


I'm trying to add specific document's ref id into another document's array of object. So that I can use populate method. But somehow the array remains empty even after pushing the ref. Please help me. Thank you in advance.

Here is list.js:

  const mongoose = require('mongoose');

  const User = require('./user');
  const Task = require('./task');
  const Schema = mongoose.Schema;
  // User Schema
  const ListSchema = mongoose.Schema({
    item:{
      type: String,
      required: true
    },
    purpose:{
      type: String,
      required: true
    },
    user: {
      type: Schema.ObjectId,
      ref:"User"
    },
    deadline:{
      type: Date,
      default: null
    }
  });

  const List = module.exports = mongoose.model('List', ListSchema);

task.js:

  const mongoose = require('mongoose');
  const Schema = mongoose.Schema;
  const List = require('./list');
  // User Schema
  const TaskSchema = mongoose.Schema({
    task:{
      type: String,
      required: true
    },
    list: [{
      type: Schema.Types.ObjectId,
      ref:'List'
    }]

  });

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

Here is how I create and save new task instance:

  const express = require('express');
  const mongoose = require('mongoose');
  const router = express.Router();

  let List = require('../models/list');
  let User = require('../models/user');
  let Task = require('../models/task');

  router.post('/add', isAuthenticated, function(req,res){
    var tasker = req.body.task, listshash= [];
    var startIndex = 0, index;
      var x,y,listid= [];
      while ((index = tasker.indexOf("#", startIndex)) > -1) {
        var ind = tasker.indexOf(" ", index);
        if(ind == -1)
            listshash.push(tasker.substring(index+1));
      else  
          listshash.push(tasker.substring(index+1,ind));
          startIndex = index + 1;
      }

      //Instance of task
      var taskIns = new Task({task: req.body.task});

      List.find({user: req.session.passport.user}, function(err, lists){
      for(x in lists){
        for(y in listshash){
          if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]){
            //lists[x] contains the document "list" that I want to store as 
            //ref in list property array of task
            taskIns.list.push(lists[x]);
            //console.log(taskIns.list.push(lists[x]));

          }
        }
      }
    });
    taskIns.save(function(err, doc){
        if(err) res.json(err);
        else    {
          console.log("Saved");
          res.redirect('/lists');
      }
    });
  });
  module.exports = router;

This is how the database collection of tasks look like after inserting data: See the data


Solution

  • You should have to use async npm

    List.find({user: req.session.passport.user}, function(err, lists){
         async.each(lists ,function(x,callback){
              async.each(listhash, function(y,callback){
                   if(x.item.toLowerCase().replace(/\s/g,'') == y){
                       taskIns.list.push(x);
                   }
              });
         });
    
    
    //After that you can do save the data
      taskIns.save(function(err, doc){
            if(err) res.json(err);
            else    {
              console.log("Saved");
              res.redirect('/lists');
          }
        });
      });