Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've been banging my head with this since last night. When I add parameters to the sql, it doesn't work.

var findOne = function(username, cb) {
    pg.connect(pgURL, function(err, client, done) {
        var query = client.query('SELECT * FROM users WHERE username = $1', [username]);
        done();

        query.on('row', function(row) {
            cb(err, row);
        });
    });
};

However, if I do an SQL statement without parameterization it works just fine.

var query = client.query("SELECT * FROM users WHERE username = 'foobar'");

Also, doing a console.log(query), right after done(), yields the following:

13:48:00 web.1  | { domain: null,
13:48:00 web.1  |   _events: null,
13:48:00 web.1  |   _maxListeners: 10,
13:48:00 web.1  |   name: undefined,
13:48:00 web.1  |   text: 'SELECT * FROM users WHERE username = $1',
13:48:00 web.1  |   values: [ '{"username":"foobar"}' ],
13:48:00 web.1  |   callback: undefined,
13:48:00 web.1  |   _result: 
13:48:00 web.1  |    { command: null,
13:48:00 web.1  |      rowCount: null,
13:48:00 web.1  |      oid: null,
13:48:00 web.1  |      rows: [],
13:48:00 web.1  |      fields: [],
13:48:00 web.1  |      _parsers: [],
13:48:00 web.1  |      RowCtor: null },
13:48:00 web.1  |   _addedFields: false,
13:48:00 web.1  |   _canceledDueToError: false }

What am I doing wrong here?

share|improve this question

2 Answers 2

up vote 1 down vote accepted

Your username variable appears to be a Javascript object with key username and value foobar. Try username.username to reference just the value.

Alternatively, I highly recommend the ORM Sequelize, which sits on top of pg. Take a look here: http://sequelizejs.com/documentation#usage-raw-queries

share|improve this answer
    
Great catch. Thanks, that's exactly what the issue was. –  Ahmed Sep 15 '13 at 22:06

Are you sure username is a string? Try doing username.toString().

share|improve this answer
    
adding username.toString(), did not change results. I've added the output of console.log(query) (which I added right after done()) to the original post. –  Ahmed Sep 15 '13 at 20:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.