Home > database >  how to loop over an array and get data for each element? - with mongoose & node.js
how to loop over an array and get data for each element? - with mongoose & node.js

Time:01-20

I am trying to build a social network. I have a collection of "connections"/"friend requests". the schema is as follows:

  {
    senderId: { type: String },
    receiverId: { type: String },
    approved: { type: Boolean },
  },

when the person didn't approve the connection yet, the connection is marked with "pending". when the user enter to the website, i get all the pending connections people sent him, with this command:

    const requestsPending = await Connection.find({
      receiverId: userId,
      approved: false,
    });

the thing is, in the backend, I want to get the details of the people who send the friend requests (so I can show their name picture). I want to loop over the pending requests array, and get the extra data of the user who sent the request.

  await User.findById(requestsPending[0][senderId]);

any idea how to do it for each element? what's the best approach? or any idea how to do it more efficiently?

thank you.

CodePudding user response:

this seems to work:

var requestsPendingWithUsersData = await Promise.all(
  requestsPending.map(async (item) => {
    const userData = await User.findById(item.senderId);
    return {
      item,
      senderData: { picture: userData.picture, name: userData.username },
    };
  })
);

CodePudding user response:

await User.find({
'senderId': { $in: [
    101,102,103,...
    ]}
})

You can try something like the above, where you pass an array of senderID to $in. The $in clause is similar to like operator in SQL.

If the senderId is an ObjectId, pass them as ObjectID types

await User.find({
'senderId': { $in: [
    mongoose.Types.ObjectId(<senderID>),
    ]}
})

If the mongo Document is heavier/larger, use lean() at the end of the query. Enabling the lean option tells Mongoose to skip instantiating a full Mongoose document.

await User.find({
'senderId': { $in: [
    101,102,103,...
    ]}
}).lean()
  •  Tags:  
  • Related