通过nodejs中的pg-promise将wkt列表存储在对象中

Store list of wkt inside an object by pg-promise in nodejs

我想通过 nodejs 和 pg-promise 库将这个对象存储到 postgresql 中:

这是我的方法:

    saveLineIntoDb({
        'line': linesGeoJson,
        'date': user[i].date_created,
        'user_id': user[i].uid,
        'device_id': user[i].devid,
    });

因此我创建了 ColumnSet:

const getPoint = col => {
    const p = col.source.line
    return p ? pgp.as.format('ST_GeomFromText()', p) : 'NULL';
};

const cs = new pgp.helpers.ColumnSet([
    {
        name: 'id',
        mod: ':raw',
        init: generate_id
    },
    'device_id',
    'user_id',
    {
        name: 'created_date',
        prop: 'date'
    },
    {
        name: 'st_astext',
        mod: ':raw',
        init: getPoint
    }
], {
    table: 'scheduled_locations'
}); 

这是将我的用户对象存储到数据库中的方法:

async function saveLineIntoDb(user) {
    logger.debug(`saveIntoDatabase method started`);
    try {
        db.result(await pgp.helpers.insert(user, cs))
            .then(data => {
                logger.debug(`saveIntoDatabase method ended`); 
            });
    } catch (error) {
        logger.error('saveIntoDatabase Error:', error);
    }
}

但不幸的是,它仅将 LINESTRING 之一存储在 line 用户对象属性中。 line 属性是一个列表,如上图所示。 我认为这样 pg-promise 不能迭代对象内的内部列表,我必须单独插入。

您对 await/async 的用法是错误的。改成这样:

async function saveLineIntoDb(user) {
    logger.debug('saveIntoDatabase method started');
    try {
        await db.result(pgp.helpers.insert(user, cs));
        logger.debug('saveIntoDatabase method ended'); 
    } catch (error) {
        logger.error('saveIntoDatabase Error:', error);
    }
}

But unfortunately it just store one of LINESTRING inside line user object attribute . line attribute is a list as you can see at above image. I think in this way pg-promise can not iterate inner list inside object and I have to insert separately.

因此您对列使用方法 init,并正确设置格式。