Annonymous
Annonymous

Reputation: 45

Mongoose query to find name from array in same table and get its whole data from that table

I have one user table in MongoDB in which I save registered users data and with that I also saves its friends name in friends arrays. The schema is as per below.

const Schema = new mongoose.Schema({
  img: { type: String, ref: 'userRequest' },
  name: String,
  email: String,
  lastname: String,
  pass: String,
  phonenumber: String,
  zipcode: String,
  birthdate: String,
  friends: []
});

var user = mongoose.model('simple-chat', Schema);

In friends array the name is sets dynamically from different table.Now I want to display the list of friends of user.I can simple retrieve name of friends from this array but with name I also want to show its image too which is with persons whole data.

For example,I have 2 userdata in table 1)Userone and 2)Usertwo In userones friends array its has friendname:usertwo.Now if I want to show userones friends list,Then I need to get name from array and related name I need to find its image.How can I get the whole data of friendsname which is in friendsarray.Please suggest me any query for this.

Right now I am trying to achieve this with nested Find loop but its not able to send data to client side.

var friendname;
var friendarr = [];

app.get('/userfriendslist', (req, res) => {


  user.find({ name: loginperson }, (err, result) => {
    if (err) {
      console.log(err);
    }
    else {
      for (var i = 0; i < result.length; i++) {

        console.log("results length" + result.length)

        for (var j = 0; j < result[i].friends.length; j++) {
          if (result[i].friends[j].friendname != null) {
            console.log("result of one" + result[i].friends.length);
            friendname = result[i].friends[j].friendname;
            console.log("friend list" + friendname);
            user.find({ name: friendname }, (err, doc) => {
              console.log("total result" + doc);


              friendarr[i] = doc;

                console.log("insidefriendsarray" +friendarr[i]); 
              });
          }
          else {
            console.log("No friend found");
          }
        }
       console.log("XXXXXXX"+friendarr[i]);
            /* res.send(friendarr[i]); */ 
        }
    }
})
});

I know this is not a proper way to do such operation. In this logic, I am successfully getting friendsdata in "friendsarray console" but outside for loop the friendarray is coming null.so that I can send this array. I will be thankful if you modify my this logic, or else please suggest me to do such operation with a query.

Upvotes: 0

Views: 551

Answers (1)

Yogesh.Kathayat
Yogesh.Kathayat

Reputation: 1004

In your existing logic you can use async await which will make your code readable and instead of normal for loop you can use for...of loop to run db calls synchronously inside your loop.

app.get('/userfriendslist', async (req, res) => {
  try {
    let friendsArr = [];
    let result = await user.find({ name: loginperson });

    for (let userobj of result) {

        for (let friend of userobj.friends) {
            if (friend.friendname != null) {
                let friendname = friend.friendname;
                let userFriend = await user.find({ name: friendname });
                if (userFriend) friendsArr.push(userFriend);
            }
            else {
                console.log("No friend found");
            }
        }
    }
   console.log("friendsArr is ",friendsArr);
   } catch (err) {
    console.log(err);
 } 
});

Upvotes: 1

Related Questions