我建议在数据库端进行检查,然后将ID返回给nodejs。
例子:
CREATE OR REPLACe FUNCTION foo(p_param1 tableFoo.attr1%TYPE, p_param2 tableFoo.attr1%TYPE) RETURNS tableFoo.id%TYPE AS $$ DECLARE v_id tableFoo.pk%TYPE; BEGIN SELECT id INTO v_id FROM tableFoo WHERe attr1 = p_param1 AND attr2 = p_param2; IF v_id IS NULL THEN INSERT INTO tableFoo(id, attr1, attr2) VALUES (DEFAULT, p_param1, p_param2) RETURNING id INTO v_id; END IF; RETURN v_id: END;$$ LANGUAGE plpgsql;
而不是在Node.js端(在此示例中,我使用的是node-postgres):
var pg = require('pg');pg.connect('someConnectionString', function(connErr, client){ //do some errorchecking here client.query('SELECt id FROM foo(, );', ['foo', 'bar'], function(queryErr, result){ //errorchecking var id = result.rows[0].id; };});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)