mongodb 如何使用express Mongoose优化服务器端Nodejs的API查询

wvt8vs2t  于 2022-12-29  发布在  Go
关注(0)|答案(1)|浏览(123)

我已经创建了node.js rest API,并在共享主机服务器上部署了节点应用程序。
我有大约1000+记录在我的 Mongoose 收藏。
我面临的主要问题是,如果我在本地PC上运行后端,查询获取时间大约需要3秒,但共享主机上的代码需要5分钟以上才能完成请求。
我从多个mongoose集合中生成数据,并为我的出勤记录返回一个对象数组。

像这样,我从多个 Mongoose 收集数据。

exports.get = async function (req, res) {
  var empl = [];

  if (req.query.user_id) {
    empl = await userModel.find({ company_id: req.query.company_id, id: req.query.user_id });
  } else {
    empl = await userModel.find({ company_id: req.query.company_id });
  }
  // console.log("uesr",empl);
  var currentMonth;
  var currentYear;
  if (req.query.month) {
    currentMonth = req.query.month;
  } else {
    currentMonth = getmonth()
  }
  if (req.query.year) {
    currentYear = req.query.year;
  } else {
    currentYear = getyear();
  }
  //   console.log("month",currentMonth);
  //  console.log("year",currentYear);
  var currentYearsHoildays = [];
  var holidays = await holidaysModel.find({});
  //console.log("holidays",holidays);
  if (holidays && holidays.length > 0) {
    for (var h = 0; h < holidays.length; h++) {
      var hdate = holidays[h].date.split("/");
      //  console.log("holidays",hdate);
      //  console.log("current",currentYear);
      if (hdate[2] === currentYear.toString()) {
        //console.log("currendddddt",currentYear);
        var bb = {
          id: holidays[h].id,
          name: holidays[h].name,
          type: holidays[h].type,
          date: holidays[h].date,
          status: holidays[h].status,
          company_id: holidays[h].company_id,
        }
        currentYearsHoildays.push(bb);
      }

    }

  }


  var currentMonthDays = getDays(currentMonth);
  var leavesession = await leavesessionModel.find({ company_id: req.query.company_id, status:         1 });
  var users = [];
  var attandence = [];
  if (empl && empl.length > 0) {
    for (var u = 0; u < empl.length; u++) {
      var leavesession = await leavesessionModel.find({ company_id: empl[u].company_id, status: 1 });
      //console.log("leavesession: ", leavesession[0]?.id)
      let atd = [];
      let nobj = {};
      for (var i = 1; i <= currentMonthDays; i++) {
        if (i <= 9) {
          var k = '0' + i;
        } else {
          var k = i;
        }

        let date = k + '/' + currentMonth + '/' + currentYear;
        let obj = {};
        ///// holidays and leaves check 
        var holidayschk = await holidaysModel.find({ date: date });
        var leaves = await userleavesModel.find({ leavesession_id: leavesession[0]?.id, date:     date, user_id: empl[u].id });
        // console.log("sesion",leavesession[0].id);
        //console.log("leaves",leaves);
        /////

        const atten = await attandenceModel.find({ user_id: empl[u].id, date: date })
        if (atten && atten.length > 0 && atten[0].timein) {
          var pr = true;
          if (atten[0]?.totalhours == 'NaN') {
            pr = false;
          }
          obj = {
            id: atten[0]?.id,
            timein: atten[0]?.timein,
            timeout: atten[0]?.timeout,
                totalhours: atten[0]?.totalhours,
            date: date,
            present: pr,
            holiday: (holidayschk && holidayschk.length > 0) ? true : false,
            leave: (leaves && leaves.length > 0) ? true : false,
          }

        }
        // else if(holidayschk && holidayschk.length>0)
        // {
        //   obj ={

        //     timein:holidayschk[0]?.name,
        //     timeout:holidayschk[0]?.name,
        //     date:date,
        //     present:false,
        //     holiday:true
        //    }
        // }
        else {
          obj = {
            id: atten[0]?.timein,
            date: date,
            present: false,
            holiday: (holidayschk && holidayschk.length > 0) ? true : false,
            leave: (leaves && leaves.length > 0) ? true : false,
            timein: '-',
            timeout: '-',
            totalhours: 'NaN',
          }
        }
        atd.push(obj);
      }

      nobj = {
        id: empl[u].id,
        name: empl[u].first_name + " " + empl[u].last_name,
        image: empl[u].image,
        wrokfrom_home: empl[u].wrokfrom_home,
        attandence: atd,

      }
      attandence.push(nobj);
    }

    //console.log("atandence ",attandence);

  }
  //return res.json(attandence);

  const newobj = {
    Good: true,
    data: {
      holidays: currentYearsHoildays,
      attandence: attandence
    },
  };
  // console.log("OBJedt ",newobj);
  res.send(newobj);
};

这是我用来获取数据的代码,你们可以理解我在这里做什么。
有人知道如何优化API以获得良好的响应吗?
我试着在API中使用分页,但是如果我只获取3条记录,它也会在共享主机中花费很多时间。我想这可能是因为我的服务器端从mongoose获取数据,但不确定。

nimxete2

nimxete21#

首先,您应该通过字段company_id https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/对userModel和leavesessionModel使用$lookup聚合。嵌套循环是有害的,尤其是对于数据库查询。尝试摆脱它们。您在loop调用此查询,但只能在loop之外执行一次。

var holidayschk = await holidaysModel.find({ date: date });

先试着解决这个问题。

相关问题