创build一个键值对(从mongoDB数据库中获取)的数组

我正在尝试以dynamic的方式创build一个key-value对的数组。 values部分是从我的routes数据库中获取的。 这就是我正在做的。

  router.get('/account',isAuthenticated, function(req,res){ var following_users_details = []; for (var i = 0;i<req.user.following_users.length;i++) { var following_user = req.user.following_users[i];// following_users is a field of Array type in my MongoDB database User.findOne({'username' : following_user }, function(err,user) { following_users_details.push({ username: user.username, profilepic : user.photo, userbio : user.bio }); }); } res.render('users/userAccount',{user:req.user, following_users_details:following_users_details }); }); 

但是当我尝试打印我的key-value对的数组时,我什么也得不到。

 for(var i = 0;i<following_users_details.length;i++) { console.log("Username = "+following_users_details[i].username); console.log("Username = "+following_users_details[i].profilepic); console.log("Username = "+following_users_details[i].userbio); } 

当我尝试打印数组时,控制台上没有输出 。 我想我错过了一些非常明显的东西。 这是创build数组的正确方法还是我以错误的方式做?

PS – 我已经通过这个 , 这个和这个 ,但没有一个直接解决我的问题。

一些事情,首先是你的console.log发生之前,他们来自数据库。

第二,更好的是,不要为每个用户做所有不必要的呼叫,只需要一个呼叫。

 router.get('/account',isAuthenticated, function(req,res){ var following_users_details = []; User.find({ username: {$in: req.user.following_users} // assuming this is an array }, { // select options. This might be done differently though, // depending on your MongoDB driver/ORM username: true, profilepic: true, userbio: true }, // callback function (err, followedUsers) { // only now you have access to users, not before. Now log/send them if (err) {/* handle DB error */ res.render('users/userAccount',{ user:req.user, following_users_details: followedUsers }); // also log them to console. followedUsers.forEach(function(followedUser) { console.log(JSON.stringify(followedUser, null, 2); }); }); }); 

findOne中的callback发生在将来,它是asynchronous的。 您必须在所述callback中呈现数据才能存在。

  User.findOne({'username' : following_user }, function(err,user) { following_users_details.push({ username: user.username, profilepic : user.photo, userbio : user.bio }); res.render('users/userAccount',{user:req.user, following_users_details:following_users_details }); }); }