2015-05-29 90 views
0

我正在開發使用Nodejs和Mongodb和貓鼬的應用程序。用戶和訂閱是2貓鼬模式。我想從訂閱集合中獲取每個成員的過期日期,並將它與每個成員對象數組一起包含在內。但它不起作用。類型錯誤無法設置屬性未定義

var UserSchema = new Schema({ 
    title: { 
     type: String 
    }, 
    firstName: { 
     type: String 
    }, 
    lastName: { 
     type: String 
    }, 
    displayName: { 
     type: String 
    }, 

}); 

var SubscriptionSchema = new Schema({ 
    member_id: { 
     type: Schema.ObjectId, 
     ref: 'User' 
}, 
    renewal_date: { 
     type: Date 
    }, 
    expire_date: { 
     type: Date 

    }, 

    amount: { 
     type: String 
    }, 
    paid_mode: { 
     type: String 
    }, 

}); 





exports.memberlist = function(req, res) { 
    var expire=''; 

    user.find({}).lean().exec(function(err, collection) { 



      var i; 
      for(i=0;i<collection.length; i++) 
      { 



       Subscriptions.find({'member_id':collection[i]._id}).lean().exec(function(err, subs){ 

        if(subs.length > 0) 
         { 

          expire = subs[0].expire_date || ''; 
         collection[i].expire_date = 'expire'; 

         } 


        }); 


      } 


     res.send(collection); 

    }); 

}; 

回答

1

這是控制流問題。你應該使用類似這樣

var async = require('async'); 

// ... 

exports.memberlist = function(req, res) { 
    var expire=''; 

    user.find({}).lean().exec(function(err, collection) { 

     async.eachSeries(collection, function(item, cb){ 
      Subscriptions.find({'member_id':item._id}).lean().exec(function(err, subs){ 

       if(subs.length > 0) 
        { 

         expire = subs[0].expire_date || ''; 
         collection[i].expire_date = 'expire'; 
         cb() 
        } 


       }); 


     }, function(){ 
      res.send(collection); 
     }); 
    }); 
}; 

閱讀here有關節點控制流程,並here約異步模塊。

+0

工作。謝謝你的回答.. –

相關問題