提问者:小点点

使用knex插入数据库


我正在使用knex 0.13.0并尝试插入具有以下函数的mysql数据库:

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;
    }
}

最后一个带有create post:Title Description 1505062847788 false的控制台输出显示正确,但即使在等待之后也没有发生任何事情

  • 我猜这是函数的异步部分,但同时还能做什么呢?
  • 使用Knex时,是否有标准的方法创建条目?

感谢您的回复!


共1个答案

匿名用户

我使用的是节点6,所以现在不能测试'await'(出现在节点7中),但从这篇文章来看,您应该将await响应赋值给一个变量。如:

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

具体来说:

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;
    }
}

您所拥有的功能应该可以正常工作,但我所做的(作为您的替代方案)只是直接使用promises并构建数据访问函数,通常如下所示:

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);
    });
};

希望这有帮助!