0

I want to create a generic function which can return the username when providing the userid on that function.

I have a data structure like this:

{
  "_id": ObjectId("5a20eb5bcdacc7086ce77427"),
  "username: "John"
}

I already created a generic function but it returns undefined instead of returning username from db.

var getUserNameByUserID = (id) => {
    var username = "";
    User.find({'_id': id}, {'_id': 0, 'username': 1})
    .then(data => {
        if (data.length > 0) {
            username = data[0].username;
            //console.log(username);
            return username;
        } else {
            return username;
        }
    })
    .catch(error => {
        return username;
    })
};

//It returns undefined
console.log(getUserNameByUserID('5a20eb5bcdacc7086ce77427'));

Any help is really apreciated.

Ankit
  • 951
  • 1
  • 9
  • 29
  • Try to understand JavaScript nature, you may use callback, promise or async/await – Arif Khan May 04 '18 at 10:12
  • Dear Neil Lunn, I do the same approach as mentioned in that similar question. If I remove the MongoDB Query that uses User.find() part then it will work perfectly. All issue is on Db Query. – Ankit May 04 '18 at 11:01

1 Answers1

0

You need to cast your id in ObjectId, if it's a String you will not have result.

Nicolas
  • 457
  • 5
  • 15