代码之家  ›  专栏  ›  技术社区  ›  Ayodeji Jayeoba

带有pg promise的添加数据的多次插入

  •  1
  • Ayodeji Jayeoba  · 技术社区  · 9 年前

    我有一个大数据集,我想插入到postgres数据库中,我可以使用pg promise这样实现

    function batchUpload (req, res, next) {
        var data = req.body.data;
        var cs = pgp.helpers.ColumnSet(['firstname', 'lastname', 'email'], { table: 'customer' });
        var query = pgp.helpers.insert(data, cs);
        db.none(query)
        .then(data => {
            // success;
    
        })
        .catch(error => {
            // error;
            return next(error);
        });
    }
    

    数据集是这样的对象数组:

               [
                    {
                        firstname : 'Lola',
                        lastname : 'Solo',
                        email: 'mail@solo.com',
                    },
                    {
                        firstname : 'hello',
                        lastname : 'world',
                        email: 'mail@example.com',
                    },
                    {
                        firstname : 'mami',
                        lastname : 'water',
                        email: 'mami@example.com',
                    }
                ]
    

    挑战是我有一个专栏 added_at 数据集中不包含的,并且不能 null

    1 回复  |  直到 9 年前
        1
  •  2
  •   vitaly-t    5 年前

    根据 ColumnConfig

    const col = {
        name: 'added_at',
        def: () => new Date() // default to the current Date/Time
    };
        
    const cs = pgp.helpers.ColumnSet(['firstname', 'lastname', 'email', col], { table: 'customer' });
    

    或者,您可以用多种其他方式定义它,如 ColumnConfig 非常灵活。

    例子:

    const col = {
        name: 'added_at',
        mod: ':raw', // use raw-text modifier, to inject the string directly
        def: 'now()' // use now() for the column
    };
    

    或者,您可以使用属性 init

    const col = {
        name: 'added_at',
        mod: ':raw', // use raw-text modifier, to inject the string directly
        init: () => {
           return 'now()';
        }
    };
    

    ColumnConfig 有关详细信息,请参阅语法。

    P、 我是 pg-promise .

    推荐文章