Search code examples
javascriptmysqlknex.js

Insert into database using knex


I am using knex 0.13.0 and I am trying to insert into a mysql database with the following function:

async function create(title, description) {
    //trim spaces
    console.log("title: " + title)
    console.log("description: " + description)
    title = title.trim()
    description = description.trim()
    createdAt = _.now()
    deleted = false
    console.log("Create Post: " + title + " " + description + " " + createdAt + " " + deleted)

    if (title.length < 1 || title.length > 255) throw new Error('Title is not valid.')
    if (description.length < 1) throw new Error('Description is not valid.')

    try {
        await knex('posts').insert({
            title,
            description,
            createdAt,
            deleted
        })
        console.log("added to db")
        return true;
    } catch (e) {
        return "An error occured: " + e;
    }
}

The last console output with Create Post: Title Description 1505062847788 falseis shown right, but nothing is happening, even after waiting

  • I guess it is the asynch part of the function, but what else to do in the meanwhile?
  • Is there a standard way to create an entry when using knex?

Appreciate your reply!


Solution

  • I'm using Node 6, so can't test 'await' at the moment (came in node 7) but from this post it looks like you should assign the await response to a variable. Like:

    ...        
    var awResponse; // new variable
    try {
        awResponse = await knex('posts').insert({
    ...
    

    In detail:

    async function create(title, description) {
        //trim spaces
        console.log("title: " + title)
        console.log("description: " + description)
        title = title.trim()
        description = description.trim()
        createdAt = _.now()
        deleted = false
        console.log("Create Post: " + title + " " + description + " " + createdAt + " " + deleted)
    
        if (title.length < 1 || title.length > 255) throw new Error('Title is not valid.')
        if (description.length < 1) throw new Error('Description is not valid.')
    
        var awResponse; // new variable
        try {
            awResponse = await knex('posts').insert({
                title,
                description,
                createdAt,
                deleted
            })
            console.log("added to db")
            return true;
        } catch (e) {
            return "An error occured: " + e;
        }
    }
    

    What you have should work just fine, but what I've been doing (as an alternative for you) is just directly using promises, and constructing my data access functions generally as follows:

    function create(title, description) {
        return Promise.resolve().then(function () {
            // This first section is for preping the record for insert.
            //
            //trim spaces
            console.log("title: " + title)
            console.log("description: " + description)
            title = title.trim()
            description = description.trim()
            // createdAt = _.now()  // I have a error that "_" is not valid
            createdAt = (new Date()).toISOString();
            deleted = false
            console.log("Create Post: " + title + " " + description + " " + createdAt + " " + deleted)
    
            if (title.length < 1 || title.length > 255) throw new Error('Title is not valid.')
            if (description.length < 1) throw new Error('Description is not valid.')
            return { "title": title,
                     "description": description,
                     "createdAt": createdAt,
                    "deleted": deleted };
        })
        .then(function (recordToInsert) {
            // This second section is for the insert.
            //
            console.log("Part #2");
            return knex('posts').insert(recordToInsert)
            .on('query-error', function(ex, obj) {
                // console.log("KNEX query-error ex:", ex);
                // console.log("KNEX query-error obj:", obj);
                // Below logs db errors into my custom encapsulation of winston logging.
                //       ... and the .catch further down will still be executed.
                log.logMsg('error', "DBA.INS88", "KNEX create.on.query-error", {"fnc": "create", "obj":obj, "ex":ex} );
            })
        })
        .then(function (insertResult) {
            // This third section is for post-processing the result (if needed).
            //
            console.log("Part #3 added to db :", insertResult);
            return insertResult; // returns id value from insert;
        })
        .catch(function (e) {
            // I omit this .catch to let the caller know about and handle the exceptions
            console.log( "An error occured: " + e);
        });
    };
    

    Hope this helps!