2017-01-05 55 views
1

我需要在postgres數據庫中插入/更新點列類型。將POINT插入postgres數據庫

我使用node-postgres

使用POSTGRES管理面板生成的腳本顯示瞭如何實現從緯度和經度點更新查詢作爲

UPDATE public.places SET id=?, user_id=?, business_name=?, alternate_name=?, primary_category=?, categories=?, description=?, address=?, city=?, state=?, country=?, zip=?, point WHERE <condition>;

我已經看到幾個使用POSTGIS的答案,但無法讓它工作。我們可以使用point '(2,1)',但這不適用於pg查詢。

我現在擁有的一切:

var config = { 
    user: 'postgres', 
    database: 'PGDATABASE', 
    password: 'PGPASSWORD!', 
    host: 'localhost', 
    port: 5432, 
    max: 10, 
    idleTimeoutMillis: 30000 
}; 

以及更新部分:

app.post('/updatePlaces', function(req, res, next) { 
    console.log("Update"); 
    console.log(req.body.places); 
    pool.query('UPDATE places SET address = $1, alternate_name = $2, business_name = $3, categories = $4, city = $5, country = $6, description = $7, point = $8, primary_category = $9, state = $10, zip = $11', [req.body.places.address, req.body.places.alternate_name, req.body.places.business_name, req.body.places.categories, req.body.places.city, req.body.places.country, req.body.places.description, (req.body.places.point.x, req.body.places.point.y), req.body.places.primary_category, req.body.places.state, req.body.places.zip], function(err, result) { 
     if(err) { 
      console.log(err); 
      return err; 
     } 

     res.send(result.rows[0]); 
    }); 
}); 

嘗試過許多不同的方式爲通過點:

  1. (req.body.places.point .x,req.body.places.point.y)
  2. point(req.body.places.point.x,req.bod y.places.point.y)
  3. 點 '(2,1)'

所有上述拋出錯誤。我需要使用POSTGIS嗎?

+0

使用[pg-promise](https://github.com/vitaly-t/pg-promise)時可以自動完成。如果你有興趣,那麼我會用例子添加一個答案;) –

+0

是的請@ @ vitaly-t –

回答

2

經過幾次組合後,發現這個作品。

('(' + req.body.places.point.x + ',' + req.body.places.point.y +')')

發佈的答案,如果有人試圖這樣做只是使用node-postgres

所以,你可以使用單引號點:insert into x values ('(1,2)');

但在查詢中使用insert into x values (point(1,2));不起作用。

1

,如果你寫SQL 「直接」 這個作品:如果您正在使用pg-promise

CREATE TEMP TABLE x(p point) ; 
INSERT INTO x VALUES ('(1,2)'); 
INSERT INTO x VALUES (point(3, 4)); 
SELECT * FROM x ; 

結果

(1,2) 
(3,4) 
1

,然後自定義類型,可以自動格式化,請參閱Custom Type Formatting

您可以介紹一下你自己的類型是這樣的:

function Point(x, y) { 
    this.x = x; 
    this.y = y; 

    // Custom Type Formatting: 
    this._rawDBType = true; // to make the type return the string without escaping it; 

    this.formatDBType = function() { 
     return 'ST_MakePoint(' + this.x + ',' + this.y + ')'; 
    }; 
} 

在某些時候你會創建對象:

var p = new Point(11, 22); 

然後你就可以用這些變量定期類型:

db.query('INSERT INTO places(place) VALUES(ST_SetSRID($1, 4326))', [p]); 

另請參閱:Geometry Constructors

+0

Thanks @ vitaly -t我還有一個問題,我的數據庫更多是面向位置的,我應該使用postGIS嗎? –

+1

是的,這通常是一個好主意,因爲PostGIS現在像PostgreSQL的本地組件一樣,提供了基於位置的搜索所需的所有智能搜索;) –

+0

很酷。謝謝。 :) –