如何减少查询 MongoDb 以获取用户通知所需的时间?

问题描述 投票:0回答:1

登录后,我获取并返回用户的消息,然后在前端过滤“未读”以在通知铃顶部显示红色警报图标。完成请求的时间是13s。

我相信延迟是由于 api 端点造成的,我在其中循环用户的联系人以查询他们的消息。

不确定索引是否会加速这个过程......

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 })
    ),
  );
};

我无法确定任何其他解决方案。

reactjs mongodb mongoose mern
1个回答
0
投票

我希望它能减少 api 查询所花费的时间。

改进耗时的建议

  1. 减少查询的数据量,使用分页。
  2. 您经常使用的查询过滤器的索引。
© www.soinside.com 2019 - 2024. All rights reserved.