我如何管理Node Js和MongoDb上的异步回调。我的for循环工作正常。这是我的代码:
User.count( function(err, count){
console.log('counting'+ count);
for(let nbUsersWithTeams=0; nbUsersWithTeams<count; nbUsersWithTeams=nbUsersWithTeams+6){
Team.create({},
function(err, team){
if(err) return res.boom.badImplementation(err);
console.log('The id of the new team is', team._id)
/*Team.findOne({_id: team._id }).exec(
function(err, team){
if(err) return res.boom.badImplementation(err);
this.newTeam=team;
}
); */
i=0;
for(let i = 0 ; i < 12 ; i++){
User.distinct( "_id" ).exec(function( err, result) {
if (err) return res.boom.badImplementation(err.message);
var randomId = result[Math.floor(Math.random() * (count-1))];
User.findOne({_id: randomId}).exec(
function( err, user) {
if (err) return res.boom.badImplementation(err.message);
user.team=team._id;
user.save( function(err) {
if (err) return res.boom.badImplementation(err.message);
console.log('nb users in teams so far'+nbUsersWithTeams);
console.log('the i is'+ i);
console.log('push');
team.members.push(mongoose.Types.ObjectId(user._id));
team.save(function(err) {
if (err) return res.boom.badImplementation(err.message);
});
});
//nbUsersWithTeams=nbUsersWithTeams+1;
}
);
});
}
});
}
});
我想让我的每个团队完全加入12个人,但我会吸引更多的人。我认为这是由于来自mongoDb的异步回调。
以下是架构:
对于用户:
var userSchema = new Schema({
email : {
type: Schema.Types.String, required: true
},
displayName : {
type: Schema.Types.String, required: true
},
team : {
ref : 'Team',
type : Schema.Types.ObjectId
},
picture : { /// url picture
type : Schema.Types.String
},
piecesVersionGamer : [
{
piece : {
ref:'Piece',
type: Schema.Types.ObjectId
},
date : {
type : Schema.Types.Date, default: Date.now
}
}
],
badges: [
{
photoPuzzle : {
ref: 'PhotoPuzzle',
type: Schema.Types.ObjectId,
},
date : {
type : Schema.Types.Date, default : Date.now
}
}
]);
对于团队:
export class Team{
_id : any;
photoPuzzle : string;
piecesNotFound : string[];
members : string[];
}