Search code examples
javascriptknex.js

Insert faker data via knex


I want to insert data via knex using a for look to create an object to insert data.

I tried the following:

const faker = require('faker');
const dataLength = 10
const obj = []

exports.seed = function (knex, Promise) {
  // Deletes ALL existing entries
  return knex('posts').del()
    .then(function () {
      //create entries
      for (var index = 0; index < dataLength; index++) {
        obj[index] = {
          title: faker.lorem.sentence(),
          description: faker.lorem.paragraph(),
          createdAt: faker.date.recent(),
          updatedAt: faker.date.recent(),
          deletedAt: faker.date.recent(),
          deleted: faker.random.boolean(),
          tags: faker.random.arrayElement(["tag1", "tag2", "tag3", "tag4"])
        }
        knex('posts').insert([,
          obj[index]
        ]);
      }
      // Inserts seed entries
      return 
    });
};

My problem is that no data get saved to the db.

Any suggestions what I am doing wrong here?


Solution

  • Your call to knex.insert() returns a promise. You need to include this promise in the promise chain by returning it inside the handler you pass to the then method. By returning a promise inside the then handler, you are effectively telling it to wait for that promise to resolve. Because you are returning nothing (specifically, undefined), your seed function deletes the posts but does not need to know it has to wait for any other operations to finish before completing.

    In the future, if you had multiple promises to return, you could use Promise.all() to return all of them:

    exports.seed = function (knex, Promise) {
      return knex('posts').del()
        .then(function () {
          return Promise.all([
            knex('bar').insert(),
            knex('foo').insert(),
          ])
        })
    };
    

    Then your promise chain would wait for all the promises inside Promise.all() to resolve before continuing.

    In this particular case, however, there's no need to call knex.insert() multiple times because it can accept an array of objects instead of a single object:

    exports.seed = function (knex, Promise) {
      return knex('posts').del()
        .then(function () {
          const posts = []
          for (let index = 0; index < dataLength; index++) {
            posts.push({
              title: faker.lorem.sentence(),
              description: faker.lorem.paragraph(),
              createdAt: faker.date.recent(),
              updatedAt: faker.date.recent(),
              deletedAt: faker.date.recent(),
              deleted: faker.random.boolean(),
              tags: faker.random.arrayElement(["tag1", "tag2", "tag3", "tag4"])
            })
          }
          return knex('posts').insert(posts)
        });
    };