skip to Main Content

Upon login I fetch and return the user’s messages, then filter for ‘unread’ on the frontend to display a red alert icon on top of a notification bell. The time it takes to complete the request is 13s.

I believe the latency is due to the api end-point, where I loop the user’s contacts to query their messages.

Not sure if an index would speed up the process…

const getMessagesByUserId = async (req, res, next) => {
  const userId = req.params.userId;
  const authUserId = req.userData.userId;

  //verify the query supplied user id against the decrypted user id.
  if (userId !== authUserId) {
    return next(new HttpError("Unauthorized access, please try again", 401));
  }

  let contactsMessages = [];

  try {
    //queries for users contacts
    const usersContacts = await User.findById(userId).populate("contacts");

    //queries and returns contacts' messages
    const userContactsMessages = await Promise.all(
      usersContacts.contacts.map(async (contact) => {
        const messages = await Contact.findById(contact["_id"]).populate(
          "messages"
        );
        contactsMessages.push(...messages.messages)
      })
    );

  } catch (error) {
    console.log(error)
    return next(
      new HttpError("Fetching messages failed, please try again.", 500)
    );
  }

  //checks if contacts message array is empty
  if (!contactsMessages || contactsMessages.length === 0) {
    res.json({ messages: [] }).status(200).end();
    return;
  }

  res.json(
   contactsMessages.map((message) =>
      message.toObject({ getters: true })
    ),
  );
};

I have not been able to identify any other solutions.

2

Answers


  1. I hope its decrease the time taken for api query .

    Suggestions on improving the time taken .

    1. Reduce the amount of data being queried , use pagination.
    2. Index on the query filters you frequently use.
    Login or Signup to reply.
  2. In the following query which you’re making in the loop to the database would increase the time taken by the API, this would result in multiple trips to the database.

    const messages = await Contact.findById(contact["_id"]).populate(
              "messages"
            ); // THIS SECTION HERE IS THE ISSUE
    

    Instead, since you already know all the "_ids" of the contact, you can use $in operator to optimise this and fetch all records in one query.

    You can take reference of this SO question for how to use the _id
    How to get multiple document using array of MongoDb id?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search