4

my data structure schema is like

users(
  id serial primary key,
  data json
);

I want to update data key.

I'm using node-postgres library and So far I have tried something like this:

pg.connect(process.env.DATABASE_URL, function(err, client, done) {
    var queryString = "UPDATE users SET data =" + myNewJsonData + " WHERE  id = " + userIdToEdit + ";";
    client.query(queryString, function(err, result) {
        done();
        if (err) {
            res.send("Failed to update user data ");
            throw err;
        } else {
            res.send("Successfully updated user data!! ");
        }
    });
});

this is not working, I'm getting error invalid input syntax for type json

Can anyone help, Thanks.

4
  • You are asking the wrong question. The right one should be: Here's the complete UPDATE, what is wrong with the syntax around the JSON column? And you don't even include what myNewJsonData is. Commented Apr 24, 2017 at 9:27
  • Its because I'm not very sure with my approach here. Commented Apr 24, 2017 at 9:29
  • But your question is about the syntax issue, not the approach. Strictly speaking, the approach will work, if you escape everything correctly. But that's a separate question altogether. Commented Apr 24, 2017 at 9:31
  • ah man you are right, it was syntax issue, got it working finally. Thanks Commented Apr 24, 2017 at 9:34

1 Answer 1

7

So it was a syntax error, All I had to do stringfy json data and put that in 'quotes'

pg.connect(process.env.DATABASE_URL, function(err, client, done) {
var newJsonDataStringyfied = JSON.stringify(myNewJsonData)
var queryString = "UPDATE users SET data = '" + newJsonDataStringyfied + "' WHERE  id = " + userIdToEdit + ";";
    client.query(queryString, function(err, result) {
        done();
        if (err) {
            res.send("Failed to update user data ");
            throw err;
        } else {
            res.send("Successfully updated user data!! ");
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.