使用 pg-promise 进行附加数据的多次插入

Multiple insertion with addition data with pg-promise

我有一个大型数据集,我想将其插入到 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。如何为查询中的每个记录插入添加时间戳。

根据 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.S。我是 pg-promise.

的作者