我正在使用Nodejs和Mongodb以及mongoose开发应用程序。 user和Subscriptions是2个mongoose模式。我希望从订阅集合中获取每个成员的过期日期,并将其包含在每个成员对象数组中。但它没有用。
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);
});
};
答案 0 :(得分: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);
});
});
};