Select object created between two dates by Bookshelf, MySQL, Knex on node.js

5.8k views Asked by At

I need to get a list of an object created between two times;

I am able to get data by writing SQL Query;

But I need to write this query by Bookshelf;

My simple query:

    router.route('/locations')
  // fetch all locations
  .get(function (req, res) {
    Locations.forge()
    .fetch()
    .then(function (collection) {
      res.json({error: false, data: collection.toJSON()});
    })
    .catch(function (err) {
      res.status(500).json({error: true, data: {message: err.message}});
    });
  })

how can I get location between two dates like above query?

1

There are 1 answers

4
flaviodesousa On BEST ANSWER

Try adding a query() call to the chain, like

Locations
  .forge()
  .query(function(qb) {
    qb.whereBetween('creation', [initialDate, finalDate]);
  })
  .fetch()
  .then(function (collection) {
    res.json({error: false, data: collection.toJSON()});
  })
  .catch(function (err) {
    res.status(500).json({error: true, data: {message: err.message}});
  });

See Bookshelf Collection.query() and Knex Query Builder and whereBetween()