1

Visit.js - Notice that folloup.id refer to 0 or "n" Visits (like tree)

var visitSchema = new Schema({
  code : {type: String, trim: true, required: false, default: ""},
  Client : {
    id: {type: Schema.Types.ObjectId, ref: 'Client'},
  },
  attendant : [{
    name : {type: String, trim: true, required: false, default: ""},
  }],
  followup : [{ 
    id : {type: Schema.Types.ObjectId, ref: 'Visit'}
  }],
});

Client.js

var clientSchema = new Schema({
  name: {type: String, trim: true, required: false, default: ""}
});

So, I tried do that but it does not working. Why not?

Visit.find(function(err, visits) {
  var visitCards = new Array();
  async.eachSeries(visits, function(visit, callback) {
    var visitCard = new VisitCard();
    async.series([
      function(callback){
        Client.findById(visit.Client.id, function(err, client) {
          visitCard.client = client.name;
          callback();
        });
      },
      function(callback){
        visit.followup.forEach(function(followup){
          Client.findById(followup.Client.id, function(err, lfollowup) {
            var pfollowup = new visitCard.followup();  
            ...
            visitCard.followup.push(pFollowup);
            callback();
          });
        });
      }
    ],
    function(err, results){
      ...
      visitCards.push(visitCard);
    });
  },
  function(err){
    res.render('visits/index', { visitCards: visitCards});
  });
});

It seems that:

Client's callback return after "async.eachSeries(visits, function(visit, callback)" execute.

"visit.followup.forEach" finished before Client.findById execute.

1 Answer 1

1

forEach is executed in parallel, SO that forEach is finished before Client.findById.

So you can use eachSeries instead of forEach.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.