简体   繁体   English

使用knex插入数据库

[英]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: 我正在使用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;
    }
}

The last console output with Create Post: Title Description 1505062847788 false is shown right, but nothing is happening, even after waiting 最后显示带有Create Post: Title Description 1505062847788 false控制台输出Create Post: Title Description 1505062847788 false正确显示,但是即使等待,也没有任何反应

  • 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? 使用knex时是否有标准的方法来创建条目?

Appreciate your reply! 感谢您的回覆!

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. 我正在使用节点6,因此目前无法测试“等待”(出现在节点7中),但是从本文看来,您应该将等待响应分配给变量。 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: 您所拥有的应该可以正常工作,但是我一直在做的事情(作为您的替代选择)只是直接使用promise,并且通常按以下方式构造我的数据访问功能:

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! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM