javascript - 使用 knex 插入数据库

标签 javascript mysql knex.js

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

感谢您的回复!

最佳答案

我正在使用节点 6,因此目前无法测试“等待”(来自节点 7),但来自 this post看起来您应该将等待响应分配给变量。喜欢:

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

你所拥有的应该工作得很好,但我一直在做的(作为你的替代方案)只是直接使用 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);
    });
};

希望这有帮助!

关于javascript - 使用 knex 插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46143320/

相关文章:

javascript - 欢呼。过滤器()?这段代码没有运行的原因是什么?

PHP MYSQL 查询组合并添加两个相等的结果

mysql - CakePHP(子)查询以获取每个组的最年轻记录

javascript - 使用 knex.js 查询多个表

javascript - 循环中的异步调用延迟

javascript - Knex 从多个表中选择

javascript - Node.js 插件中的回调函数

javascript - 在 javascript 中将 ISO 日期转换为日期格式为长日期格式

javascript - MarkerWithLabel.js - labelText 没有为标记标签创建文本?

c# - 如何使用C#设置环境变量Path