a blog for those who code

Monday 2 May 2016

Insert, Update and Delete Data with Knex in Node.js

In this post we will be discussing about Inserting, Updating and deleting data from the database using Knex. In your previous posts we have discussed about Selecting Data using Knex but most of the application needs to be able to insert, delete and update the data, so in this post we will see how easily we can do it using Knex.

Insert In Knex


Similar to SQL, Knex also has a insert method which you can use to add records to the table. At first we will create objects having the values which we need to insert into the database as shown below.

var insert1 = {col1: "a4", col2: "b4", col3: "c4"}
var insert2 = {col1: "a5", col2: "b5", col3: "c5"}

Now we will add these values to the database as shown below. In the below code at first we are creating objects and then using insert method we are inserting the data in table test and after that logging the newly inserted id.

var knex = require("knex")(knexConfig);
var insert1 = {col1: "a4", col2: "b4", col3: "c4"};

knex.insert(insert1).into("test").then(function (id) {
  console.log(id);
})
.finally(function() {
  knex.destroy();
});

After running the above code we will see something like below where at first we are showing what all the columns we have and then showing the Id of the newly inserted column


You can insert more than one object by passing an array of objects in your insert method as shown below

knex.insert([insert1, insert2]).into("test").then(function (id) {
  console.log(id);
})
.finally(function() {
  knex.destroy();
});

Delete In Knex


Similar to SQL, Knex also has a delete (or del) method which you can use to delete records to the table. In the below code we want to delete record based on a condition that the col1 value should be "a4", so for that at first we will write a where method and then call the del method as shown below.

var knex = require("knex")(knexConfig);
knex("test").where("col1","a4").del().then(function (count) {
  console.log(count);
}).finally(function () {
  knex.destroy();
});

The above code will delete all the columns which have col1 as a4 and then log the number of rows deleted as shown below .


Update in Knex


Similar to delete method we will first query and select the record using where method and then call the update method with parameters you want to update.

var knex = require("knex")(knexConfig);
knex("test").where("col1","a3")
  .update({col2: "b3new"}).then(function (count) {
console.log(count);
}).finally(function () {
knex.destroy();
});

The above code will update column col2 to b3new which have col1 as a3 and then log the number of rows updated as shown below .


Please Like and Share CodingDefined.com Blog, if you find it interesting and helpful.

No comments:

Post a Comment