0

I want to store this object into postgresql by nodejs and pg-promise library : enter image description here

This is my method:

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

so in order i have created ColumnSet:

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

and

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'
}); 

This is method that sore my user object into database:

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);
    }
}

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.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
Cyrus the Great
  • 5,145
  • 5
  • 68
  • 149

1 Answers1

1

Your usage of await/async is wrong. Change it to this:

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.

So you use method init for the column, and format it correctly.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • Thanks dude to your reminder , but now i can store inner list into db by pg-promise? I used `init` and in my way just inserted one index[0] of my list. @vitaly-t – Cyrus the Great Oct 18 '18 at 15:46
  • @sayreskabir Inside `init` you can format the data according to any data structure implemented. I did not include any specific example, because you did not detail the type of structure you have for the `lines`, and it is not clear from your screenshot. – vitaly-t Oct 19 '18 at 19:18