2016-11-28 54 views
1

我有要插入到一個postgres分貝大型數據集的多個插入,我能實現這個使用PG-承諾這樣與PG-承諾加法數據

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: '[email protected]', 
       }, 
       { 
        firstname : 'hello', 
        lastname : 'world', 
        email: '[email protected]', 
       }, 
       { 
        firstname : 'mami', 
        lastname : 'water', 
        email: '[email protected]', 
       } 
      ] 

的挑戰是我所不包括的數據集,並不能nulladded_at。如何爲查詢的每個記錄插入添加一個時間戳。

+1

運行'alter table customer alter column added_at set default now();'或db上類似的設置列的默認值 –

+0

@VaoTsun感謝您的洞察。 –

回答

0

由於每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: '^', // use raw-text modifier, to inject the string directly 
    def: 'NOW()' // use NOW() for the column 
}; 

,或者你可以使用屬性init動態設置值:

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

ColumnConfig語法細節。

P.S.我是pg-promise的作者。