我正在尝试以动态方式创建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);
}
当我尝试打印数组时,控制台上没有输出任何内容。我想我错过了一些非常明显的东西。这是创建数组的正确方法还是以错误的方式进行?
答案 0 :(得分:3)
findOne中的回调将来发生,它是异步的。您必须在所述回调内部渲染数据才能存在。
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 });
});
}
答案 1 :(得分:1)
一些事情,首先是你的console.log在来自db之前发生。
其次,更好的是,不要对每个用户进行所有不必要的调用,只需要调用一次。
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);
});
});
});