简体   繁体   中英

Changing a MongoDB query into a Postgres query in Javascript

I'm having a challenge converting this query. I have had success with others but this one combines multiple fields and I need some help. This is to get the dates to create a reservation.

//convert this:

var getByDate = (restId, date) => {
  return new Promise((resolve, reject) => {
    //  create search-between dates for the date sought
    var workDate = new Date(date);
    var fromDate = new Date(workDate.getFullYear(), workDate.getMonth(), workDate.getDate());
    var thruDate = new Date(fromDate);
    thruDate.setDate(thruDate.getDate() + 1);
    Reservation.find({
        restaurant_id: restId
      })
      .where('reservation_time').gte(fromDate).lt(thruDate)
      .exec((err, reservations) => {
        resolve(reservations);
      });
  });
};

//convert into PostgreSql query:

var getByDate = function (restId, date, callback) {
  return new Promise((resolve, reject) => {
    //  create search-between dates for the date sought
    var workDate = new Date(date);
    var fromDate = new Date(workDate.getFullYear(), workDate.getMonth(), workDate.getDate());
    var thruDate = new Date(fromDate);
    thruDate.setDate(thruDate.getDate() + 1);
    client.query('SELECT * FROM reservationSchema WHERE restaurant_id = restId ;', (error, results) => { //! NEED HELP ON THIS LINE
      if (error) {
        throw error;
      }
      callback(results.rows);
    })
      // .where('reservation_time').gte(fromDate).lt(thruDate) //! old section commented out
      // .exec((err, reservations) => {
      //   resolve(reservations);
      // });
  });
};

I came up with this:

var getByDate = function (restId, date, callback) {
  return new Promise((resolve, reject) => {
    //  create search-between dates for the date sought
    var workDate = new Date(date);
    var fromDate = new Date(workDate.getFullYear(), workDate.getMonth(), workDate.getDate());
    var thruDate = new Date(fromDate);
    thruDate.setDate(thruDate.getDate() + 1);
    client.query('SELECT * FROM reservationSchema WHERE restaurant_id = $1 and reservation_time >= $2, and reservation_time < $3;', [restId, fromDate, thruDate], (error, results) => {
      if (error) {
        throw error;
      }
      callback(results.rows);
    })
  });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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