Ad

How To Iterate Over The Whole Array? And Then Update The Database

I am working on an event-related project where I need to make sure that two events can't be set in the same timings for the same venue.

For this, whenever a new event is added, I use find() to get all the events having same event venue and then iterate to check whether the new event timing slots are clashing with other events in the database with the same venue.

I am getting two errors:

1) can't set headers after they are sent

2) I think my logic of iteration is not correct, I want the array to be checked completely and then insert if the same event venue has different timings for any XYZ event.

I tried using the filter, reduce etc but can't seem to have the desired results.

_this.insert = function(req, res) {
      var obj = new _this.model(req.body);
      obj.save(function(err, item) {
        if (err && err.code === 11000) {
          res.sendStatus(400);
        }
        if (err) {
          return console.error(err);
        }
        _this.model.find({ event_ground: req.body.event_ground }, function(
          err,
          docs
        ) {
          events = docs;
          events.map(event => {

            if (event.event_date_time && event.event_end_time) {
              endTimeofEvent = moment(event.event_end_time);
              timeofEvent = moment(event.event_date_time);
              let isStartTime = moment(req.body.event_date_time).isBetween(
                timeofEvent,
                endTimeofEvent
              );
              debugger
              let isEndTime = moment(req.body.event_end_time).isBetween(
                timeofEvent,
                endTimeofEvent
              );
              debugger
              if (isStartTime === false && isEndTime === false) {
                console.log('DB UPDATED');
                debugger
                _this.userModel.updateOne(
                  {
                    _id: req.params.id
                  },
                  {
                    $push: {
                      events: item._id
                    }
                  },
                  function(err) {
                    if (err) {
                      res.status(404).json('Something Went Wrong');
                    }
                    res.sendStatus(200);
                  }
                );
                debugger
              } 
              if(isStartTime === true || isEndTime === true) {
                console.log('DB WONT BE UPDATED');
                res.status(400).json({
                  success: false,
                  msg:
                    'This Venue is booked from ' +
                    timeofEvent.format('LLL') +
                    ' & ' +
                    endTimeofEvent.format('LLL'),
                  status: false
                });
              }
            }
          });
        });
      });
    };

If the events with the same name do not have time clash, the new event gets added, else if says event can be added, etc.

Ad

Answer

1) can't set headers after they are sent

function(err) {
   if (err) {
      res.status(404).json('Something Went Wrong');
   }
      res.sendStatus(200);
}

res.json() does not end the script. Always use return res.json() or add else condition if you don't want the code below executes.

2) I think my logic of iteration is not correct, I want the array to be checked completely and then insert if the same event venue has different timings for any XYZ event.

You are running map to iterate all the result but instantly update database once the condition matched (isStartTime === false && isEndTime === false).

It's fine if you have exactly one record but fail if the duplicate record is not the first result. I think it is better for you to do the condition check when searching database. If you have good reason to not filter when searching database, I suggest you to do as below:

let duplicate = events.filter(event => {
    // filter records that match (isStartTime === true || isEndTime === true)
});
if (duplicate.length > 0) {
    // return error message
} else {
    // update database
}
Ad
source: stackoverflow.com
Ad