简体   繁体   English

如何将 MongoDB 对象推入全局数组而不覆盖它?

[英]How do you push MongoDB objects into a global array without it overwriting?

I am having a scoping issue.我有一个范围界定问题。 First, I am searching for the current user and once I find his or her object, I access their friends array.首先,我正在搜索当前用户,一旦找到他或她的 object,我就会访问他们的朋友数组。 Within that friends array, the usernames of each friend is stored.在该朋友数组中,存储了每个朋友的用户名。 Then, I attempt to do a forEach loop on that friends array and try to add each found friend object into an array called friendsObjArr.然后,我尝试在该朋友数组上执行 forEach 循环,并尝试将每个找到的朋友 object 添加到名为 friendsObjArr 的数组中。 When I test it with one friend and the res.json statement inside the last else statement, it works.当我与一位朋友和最后一个 else 语句中的 res.json 语句对其进行测试时,它可以工作。 However I need it to be outside of the loop, so every friend is pushed.但是我需要它在循环之外,所以每个朋友都会被推。 And the problem is, after the loop ends, the data in the array is gone too.问题是,循环结束后,数组中的数据也消失了。 Here is my code:这是我的代码:

function getFriends(req, res){
    const username = req.params.userId
    let friendsObjArr = []
    User.findOne({username: username}, (err, foundUser) => {
        if (err){
            console.log(err);
        }
        else {
            foundUser.friends.forEach(friend => {
                User.findOne({username: friend}, (err, foundFriend) =>{
                    if (err){
                        console.log(err);
                    }
                    else{
                        console.log(foundFriend);
                        friendsObjArr.push(foundFriend)   
                    }
                })
            });
            res.json(friendsObjArr)
        }
    })
    
}

I would suggest you leverage MongoDB's aggregation pipeline to help you find and group users instead of doing the looping yourself.我建议您利用 MongoDB 的聚合管道来帮助您查找和分组用户,而不是自己进行循环。 You may incur performance issue in your js code for iterating objects and querying db everytime.您可能会在每次迭代对象和查询数据库的 js 代码中遇到性能问题。

Here is a MongoDB playground for your reference.这是一个MongoDB 操场供您参考。

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

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