简体   繁体   English

NodeJS / Mongoose:在forEach循环中推送值后数组变空

[英]NodeJS/Mongoose: Array is getting empty after pushing values in forEach loop

I am using Mongoose Reference Schema and trying to get all entities of the current user, and pushing it to the array, but after forEach loop ends, the array is getting empty我正在使用ZCCADCDEDB567ABAE643E15DCF0974E503Z 参考架构并尝试获取当前用户的所有实体,并将其推送到数组,但在 forEach 循环结束后,数组变空

let entityList = [];

Entity.find({})
      .populate('host')
      .exec( function(err, entities)
      {
            //Iterate through each entity, find if it belongs to current user
            //If it belongs, add to the list
            entities.forEach((entity)=>
            {
                  console.log(entity);
                  console.log(entity.host._id);
                  if(entity.host._id == req.params.id){
                        console.log("Found");
                        entityList.push(entity);
                        console.log(entityList);    //Printing the value
                  }
            });
      });
//Not being logged
entityList.forEach((i)=>{
      console.log(i);
});
console.log(entityList); //Empty array

EntitySchema:实体架构:

const entitySchema = new Schema({
      username: String,
      userType: String,
      host: { 
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
      }
});

const Entity = mongoose.model("Entity",entitySchema);

UserSchema:用户架构:

const userSchema = new Schema({
      socialMediaID: String,
      username: String,
      thumbnail: String
});

const User = mongoose.model("User",userSchema);

The exec() function returns immediately. exec() function 立即返回。 Your code continues with logging entityList .您的代码继续记录entityList But at that time the list is still empty.但当时名单还是空的。

The callback, which fills entityList , is called sometimes later (asynchronously).填充entityList的回调有时会在稍后(异步)调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM