How to add a new object to a table using objection.js and knex.js?

566 Views Asked by At

I want to add a new object to a table using Objection.js and knex.js. I wrote this code:

const Provider = require('../models/provider);

Provider
.query()
.where('ProviderName', name)
.then((data) => {
  if (data.length === 0) {
    Provider
      .query()
      .insert({ ProviderName: name,
        ProviderWebSite: webSite,
        ProviderContact: contact,
        ProviderStatus: status })
      .then(() => {
        res.render('results', { result: req.body });
      });
  } else {
    res.render('results1');
  }
})
.catch(() => {
  res.render('404');
});

The problem that the page still reload and I didn't get the page results and the table still empty.

1

There are 1 best solutions below

0
On BEST ANSWER

You seem to be missing at least one return from your promise chain, but to get the error why this fails you would need to printout what error was thrown when your catch block is emitting 404.

Probably this gives you a bit more info:

const Provider = require('../models/provider');

Provider
  .query()
  .where('ProviderName', name)
  .first()
  .then(result => {
     if (!result) {
       return Provider
        .query()
        .insertAndFetch({
          ProviderName: name,
          ProviderWebSite: webSite,
          ProviderContact: contact,
          ProviderStatus: status 
        });
      }
      return result;
  })
  .then(() => {
    // before rendering views, making sure that correct data was fetched
    res.send('result ' + JSON.stringify(result, null, 2));
  })
  .catch(err => {
    // print out error to be able to debug your problem
    res.send('404 ' + err.stack);
  });