Search code examples
javascriptnode.jsapinode-async

NodeJS sending shuffled data as API response


I have written an API endpoint which sends back the username of n number of users as response after going through an array which contains n number of user id's. Here is the code that I am talking about,

//Fetch username of user
app.post('/users/uname', (req, res) => {
    const uidArr = req.body.uid
    const len = uidArr.length
    var unameArr = []
    for(var i=0;i<len;i++){
        User.findById(uidArr[i]).then((user) => {
            if(!user){
                unameArr[i] = ""
            }

            unameArr.push(user.username)
            if(unameArr.length==len){
                res.send(unameArr)
            }
        }).catch((error) => {
            unameArr[i] = ""
        })
    }
})

I have two users in the MongoDB database with usernames 'user_one' and 'user_two'. When I send an API request to this endpoint using Postman the response which I get is shuffled. Here is an example,

I pass the following array,

{
    "uid": [ "5e481bd2151b8f156208c9dc", "5e481bd2151b8f156208c9dc", "5e481a4322495115113c1b46", "5e481bd2151b8f156208c9dc", "5e481bd2151b8f156208c9dc", "5e481a4322495115113c1b46" ]
}

and the request I expect is the following based on the position of elements on the array send as request,

[
    "user_one",
    "user_one",
    "user_two",
    "user_one",
    "user_one",
    "user_two"
]

But the actual output that I get is mixed as shown in the screenshots from Postman,

API Call one | API Call two | API Call three

What is the reason behind this issue and how can I fix this issue?


Solution

  • const uidArr = req.body.uid
    let uids = []
    User.find({},{'username':1,"_id":0})
    .where('_id')
    .in(uidArr)
    .then(docs=>{
        docs.forEach(doc=>uids.push(doc.username))
        console.log(uids) //send this back to client
    })