I am trying to retrieve a value from a mysql table to use it in another query but I keep getting an error because on the second query the value is not passed.
var id_customer='';
con1.query("SELECT id FROM utenze WHERE email='"+data.object.customer_email+"'", function (err, result, fields) {
if(err) throw err;
id_customer= result[0].id;
console.log(id_customer); //here id_customer has the correct value
});
console.log(id_customer); //here id_customer is empty
con2.query("SELECT ruolo FROM ruolo WHERE id_user="+id_customer, function (err, result, fields) {
if (err) throw err;
The second query will fail because id_customer remains empty.
data.object.email is correctly populated and the first query runs fine and returns a value.
What am i doing wrong? Is it related to how I retrieve the value from the first query?
EDIT: by further debugging tests result[0].id is returning the correct value
The first query will only return the id of utenze because you wrote select id from utenze , and not select * . so maybe replace id_customer= result[0].id by id_customer= result[0]
Related
I am trying to create an API route where I pass the field in a mongodb database from the URL and it seems to be that the field is not processed properly as I get no result even though the db has entries that match the query.
the url has the following format: localhost:5000/api/animal/find/stripes/yes
in a general form: localhost:5000/api/animal/find/<FIELD>/<VALUE>
The value is handled properly but the field not.
My code to execute the query is as follows:
exports.getAttributeController = (req, res) => {
const field = req.params.field;
console.log(field); //DEBUG
const value = req.params.value
console.log(value); //DEBUG
Animal.find({
field: value
}).exec((err, animal) => {
if (err || !animal) {
return res.status(400).json({
error: 'No Animals found'
});
}
res.json(animal);
});
};
If I use console.log, I see that the correct values have been sent from the URL, and if I hardcode the field like this
Animal.find({
'stripes': value
...
I get a result, only when I try to insert the field variable, I get no result. How can I fix this?
Thanks in advance
You want to evaluate the value of field, so instead you want
Animal.find({
[field]: value // note the brackets that mean use the value of `field`
}).exec((err, animal) => {
i have to "UPDATE" data in postgresql if data is already present in database and "INSERT" i.e create a new user_Id and insert data using IF condition. i have tried with this but i am not getting output. please help me if you know .
if(data.Details){
db.query('UPDATE Details SET fullName = $2,address= $3,phone = $4 WHERE user_id = $1 RETURNING *', [query, data.Details.fullName, data.Details.address, data.Details.phone],function(err,details) {
if (err) return callback(new Error('error'));
})
}else{
db.query('INSERT INTO Details(user_id,fullName,address,phone) VALUES($1,$2,$3,$4) RETURNING *', [query, data.Details.fullName, data.Details.address, data.Details.phone],function(err,details) {
if (err) return callback(new Error('error'));
})
}
If you want to get fancy, you can also use UPSERT/ON CONFLICT in Postgres 9.5 and later.
It is designed for this exact use case, and executes as a single "instruction", rather than having to do a query check whether something exists, and another one to update or insert, both in a transaction.
I need some help to clear some things up.
I have a Model:
var Event = new Schema({
event_code: String
, segments: [Segment]
});
The creation of new documents work very well like perfect. When it comes to update certain documents I ran into some troubles.
When I do this (code below): = it only updates the first document, even if the id does not match
function edit_event (id, new_name, callback) {
Event.update(id, {$set:{event_code: new_name}}, function(err, doc) {
if (err) throw err;
callback();
});
}
When I do this (code below): = it gives me an Error (see below)
function edit_event (id, new_name, callback) {
Event.findByIdAndUpdate(id, {$set:{event_code: new_name}}, function(err, doc) {
if (err) throw err;
callback();
});
}
Error when using findByIdAndUpdate: Cast to ObjectId failed for value ""58fdbde31bff83141b376508"" at path "_id" for model "Event"
Please, i'm desperate :! :/
UPDATE
I figured out that the id that i'm trying to pass get stored with "" around it, so when i am looking for document with matching ID it puts an extra pair of "" around it so it ends up like ""id""
UPDATE 2
When I am listing all my documents, it returns:
{ _id: 58fdbde31bff83141b376508,
event_code: 'TestABC',
__v: 0,
segments: [] }
Then when i store the id in an HTML form it adds extra pair of "" around it ... that's not the case with event_code. Why is that ?
Looks like you performed unneeded JSON.stringify and that's why you get quotes around the id. Calling JSON.parse should solve the issue:
Event.findByIdAndUpdate(JSON.parse(id), {$set:{event_code: new_name}}, ...
I am trying to have my code INSERT a row into my table called thoughtentries. It is in the public schema. I am able to run ths command while connected to my database using psql:
INSERT INTO thoughtentries VALUES('12/17/2016 14:10', 'hi');
The first column is of character type with length 17. The second column is of type text.
When I have my code attempt to INSERT using the same command above I get the error in my log:
ERROR: relation "thoughtentries" does not exist at character 13
STATEMENT: INSERT INTO thoughtentries VALUES('12/17/2016 14:11', 'hi');
I am using pg and pg-format to format the command. Here is my code to do this:
client.connect(function (err) {
if (err) throw err
app.listen(3000, function () {
console.log('listening on 3000')
})
var textToDB = format('INSERT INTO thoughtentries VALUES(%s, %s);', timestamp, "'hi'")
client.query(textToDB, function (err, result) {
if (err) {
console.log(err)
}
console.log(result)
client.end(function (err) {
if (err) throw err
})
})
})
How do I go about fixing this?
Have you verified that the table was, in fact, created in the public schema?
SELECT *
FROM information_schema.tables
WHERE table_name = 'thoughtentries';
Once you have verified that, I see two possible explanations remaining:
You are connecting to a different database by mistake. Verify, in the same session, with:
select current_database();
Your search_path setting does not include the public schema. If that's the case, you can schema-qualify the table to fix: public.thoughtentries
How does the search_path influence identifier resolution and the "current schema"
Aside: Save timestamps as data type timestamp, not character(17).
Actually, don't use character(n) at all:
Any downsides of using data type "text" for storing strings?
So I'm trying to query a record from a database and then put it into xml format in node.js. The programname is the primary key of the sasinfo table, so it's guaranteed that I'll only be working with one record. The problem is that when I run the code below, console.log(messagetoclient) prints this:
<messagetoclient><programname>undefined</programname><comment>undefined</comment><guid>undefined</guid></messagetoclient>
However, console.log(results) prints the this (the correct values from the record):
[ { programname: 'helloworld',
comment: 'testing',
GUID: '9b23e0f7b7da4535b99f706301539a44' } ]
Could someone help me figue out why the values of the key value pairs aren't being printed? Thanks.
query2 = connection.query('SELECT * FROM sasinfo WHERE programname = ?', [programname], function(err, results) {
if(err){
console.log(err);
}
else{
console.log(results);
messagetoclient= '<messagetoclient><programname>'+results.programname+'</programname><comment>'+results.comment+'</comment><guid>'+results.GUID+'<guid></messagetoclient>';
console.log(messagetoclient);
}
});
Try
messagetoclient= '<messagetoclient><programname>'+results[0].programname+'</programname><comment>'+results[0].comment+'</comment><guid>'+results[0].GUID+'<guid></messagetoclient>';
since results is an array.