Home > database >  Mongoose find all and update some
Mongoose find all and update some

Time:12-31

I am using node-cron to run a function every x ammount of time. In the function I want to retrieve all documents from the db and the after some conditions are met i want to change a single field in each document that meets the condition and then save/update all documents in my db.

My approach so far :

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

The problem here is that find() returns an array of mongoose documents so .save() is not a function. What is a good practise to do this ? Can anyone explain the logic to me ? Thanks in advance :)

p.s dont mention my time formating I know it is horrible and I will replace it with ISO dates in the future.

CodePudding user response:

Instead of trying to save the whole array, you might want to save each document individually. To do so, you'll have to make it wait all these possible promisses with Promise.all probably.

// ...
  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;
// ...
  • Related