简体   繁体   English

动态创建键值对数组(从mongoDB数据库中获取)

[英]Creating an array of key-value pairs(fetched from a mongoDB database) dynamically

I am trying to create an array of key-value pairs in a dynamic fashion. 我正在尝试以动态方式创建key-value对数组。 The values part is fetched from the database inside my routes . values部分是从我的routes内的数据库中获取的。 This is what I am doing. 这就是我在做什么。

   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 });
});

But when I try to print my array of key-value pairs I get nothing. 但是,当我尝试打印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);
}

Nothing gets outputted on the console when I try to print the array . 当我尝试打印阵列时,控制台上没有任何输出 I think I am missing something very obvious. 我想我缺少一些非常明显的东西。 Is this the proper way of creating the array or am I doing it in a wrong way? 这是创建数组的正确方法还是我做错了方法?

PS - I have already gone through this , this and this , but none of these address my issue directly. PS-我已经经历过thisthisthis ,但是这些都没有直接解决我的问题。

The callback in findOne happens in the future, it is async. findOne中的回调在将来发生,它是异步的。 You must render inside said callback for the data to exist. 您必须在上述回调中进行渲染,数据才能存在。

   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 });
        });
}

A few things, first one that your console.log happens before they come from db. 有几件事,首先是console.log发生在它们来自数据库之前。

Second, and better, do not do all the unnecessary calls per user, make just one call for all of this. 其次,更好的做法是,不要对每个用户进行所有不必要的呼叫,而仅对所有这些呼叫一次。

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);
    });
  });
});

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

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