繁体   English   中英

Mongoose 找到所有并更新一些

[英]Mongoose find all and update some

我正在使用 node-cron 每 x ammount 时间运行 function。 在 function 中,我想从数据库中检索所有文档,在满足某些条件后,我想更改每个文档中满足条件的单个字段,然后保存/更新我的数据库中的所有文档。

到目前为止我的方法:

const Appointment = require("../models/Appointment");
const {
  getDate,
  getMinutes,
  getHours,
  getYear,
  getMonth,
  addMonths,
} = require("date-fns");

const retrieveAllAppointmentsCron = async () => {
  const date = new Date();
  const year = getYear(date);
  const month = getMonth(date) + 1;
  const day = getDate(date);
  const hour = getHours(date);
  const minutes = getMinutes(date);
  if (month < 10) month = "0" + month;
  if (day < 10) day = "0" + day;
  if (hour < 10) hour = "0" + hour;
  if (minutes < 10) minutes = "0" + minutes;

  const nowFormDate = new Date(`${year}-${month}-${day}T${hour}:${minutes}`);
  const res = await Appointment.find()
    .select("-shopId -customerName -service -comments -email ")
    .exec();
    let cancleCounter=0;
  res.map((app) => {
    var appFormEndDate = new Date(`${app.date}T${app.endTime}`);
    if(nowFormDate>appFormEndDate)
    {
        app.active = false;
        cancleCounter++;
    }
  });
  await res.save()
  console.log(`a total of ${cancleCounter} appointments where updated to completed`)
  cancleCounter=0;
};

module.exports = {
  retrieveAllAppointmentsCron,
};

这里的问题是 find() 返回 mongoose 文档的数组 so.save() 不是 function。这样做的好习惯是什么? 任何人都可以向我解释逻辑吗? 提前致谢:)

ps 不要提到我的时间格式,我知道这很糟糕,以后我会用 ISO 日期替换它。

您可能希望单独保存每个文档,而不是尝试保存整个数组。 为此,您必须让它等待所有这些可能的Promise.all可能的承诺。

// ...
  let cancleCounter=0;
  await Promise.all(res.map(async (app) => { // <-- wait for all to solve.
    var appFormEndDate = new Date(`${app.date}T${app.endTime}`);
    if(nowFormDate>appFormEndDate)
    {
        app.active = false;
        await app.save(); // <-- save only 1 document!
        cancleCounter++;
    }
  }));
  // await res.save() <-- removed
  console.log(`a total of ${cancleCounter} appointments where updated to completed`)
  cancleCounter=0;
// ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM