代码之家  ›  专栏  ›  技术社区  ›  Cyrus the Great

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

  •  0
  • Cyrus the Great  · 技术社区  · 7 年前

    我想通过nodejs和pg promise库将此对象存储到postgresql中: enter image description here

    这是我的方法:

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

    const getPoint = col => {
        const p = col.source.line
        return p ? pgp.as.format('ST_GeomFromText($1)', 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就不能在对象内部迭代内部列表,必须单独插入。

    1 回复  |  直到 7 年前
        1
  •  1
  •   vitaly-t    7 年前

    您使用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);
        }
    }
    

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

    init ,并正确设置其格式。