1

我有一个要插入到 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. 如何为查询中的每个记录插入添加时间戳。

4

1 回答 1

2

根据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语法。

PS 我是pg-promise的作者。

于 2016-11-28T09:29:37.173 回答