Im trying to get the rowid from the database where there is someone with the same username from the guy who just wrote a message. The code works when I change
WHERE creator` =${member.username} to WHERE matchid =` ${matchid}.
It gets me the rowid from that match. But I want to get the rowids from where the user is the creator. (I checked my db and on the creator column there is the name of the username Boanak). The error that im getting is this: { Error: SQLITE_ERROR: no such column: Boanak errno: 1, code: 'SQLITE_ERROR' }.
My code:
var getMatchid = function(client, message, callback) {
//let matchid = parseInt(args.join(' '));
let member= message.member.user;
var db = new sqlite3.Database('Matches');
db.serialize(function() {
db.all(`SELECT rowid
FROM Match
WHERE creator =`+${member.username}, function(err, allRows){
if(err) {
//console.log(err);
callback(err, null);
}
else {
callback(null, allRows);
}
db.close();
});
});
}
getMatchid(client, message, function(err, data){
if (err) {
console.log(err);
}
else if (data && data.length) {
message.channel.send(`Match ${data[0].rowid} found`);
}
else {
message.channel.send("That match ID doesnt exist.");
}
});
You need to encapsulate your variable in a string. You're also using template literals, so you can put the expression directly inside.
`SELECT rowid
FROM Match
WHERE creator = "${member.username}"`
Related
I am using the following code snippet in a Node.js application to attempt to query a (local) postgres database:
var conString = "postgres://user:password#localhost:5432/mydatabase";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {
if(err) {
return console.error('error running query', err);
}
if (typeof result.rows[0] === "undefined") {
console.log("No user/password determined in DB for login attempt");
} else {
} //user/password is 'undefined' (NOT found in database)...OR NOT...
client.end();
});
});
I am receiving an error when the query runs...I believe the problem may possibly be the number of parameters in my query call...? If that is the case (or it is some other syntax problem) could anybody be so kind to inform how I should change the code to perform the query correctly...?
I simply need to take 2 (user-supplied) results from a form (req.body.usr and req.body.pword) and compare them to the database table 'users' to determine if the credentials are correct. I already believe the database connection works properly. Any advice greatly appreciated. I thank you in advance.
Change:
client.query("SELECT * FROM users WHERE name = $1 AND cred = $2", [String(req.body.usr), String(req.body.pword)], function(err, result) {...
to:
const query = {
text: "SELECT * FROM users WHERE name = $1 AND cred = $2",
values: [String(req.body.usr), String(req.body.pword)]
};
client.query(query, function(err, result) {
Read more: https://node-postgres.com/features/queries
Hello I am new to Postgresql and I wanted to learn how one handles 0 results as an error is thrown. Essentially I want to get a user if it doesn't exist, return null if one doesn't, and have an error handler. Below is the current code I am using. Any tips on a better way to do this are appreciated!
var options = {
// Initialization Options
promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/myDbName';
var db = pgp(connectionString);
function getUser(id) {
let user = new Promise(function(resolve, reject) {
try {
db.one('select * from users where loginName = $1', id).then(function(data) {
console.log(data);
resolve(data);
}).catch (function (e) {
console.log('error: '+e);
reject(e);
});
}
catch (e) {
console.log('error: '+e);
reject(e);
}
});
return user;
}
output in console:
error: QueryResultError {
code: queryResultErrorCode.noData
message: "No data returned from the query."
received: 0
query: "select * from users where loginName = 'someUserName'"
}
I am the author of pg-promise.
In the realm of promises one uses .then to handle all normal situations and .catch to handle all error situations.
Translated into pg-promise, which adheres to that rule, you execute a database method that resolves with results that represent all the normal situations, so anything else ends up in .catch.
Case in point, if returning one or no rows is a normal situation for your query, you should be using method oneOrNone. It is only when returning no row is an invalid situation you would use method one.
As per the API, method oneOrNone resolves with the data row found, or with null when no row found, which you can check then:
db.oneOrNone('select * from users where loginName = $1', id)
.then(user=> {
if (user) {
// user found
} else {
// user not found
}
})
.catch(error=> {
// something went wrong;
});
If, however, you have a query for which returning no data does represent an error, the proper way of checking for returning no rows would be like this:
var QRE = pgp.errors.QueryResultError;
var qrec = pgp.errors.queryResultErrorCode;
db.one('select * from users where loginName = $1', id)
.then(user=> {
// normal situation;
})
.catch(error=> {
if (error instanceof QRE && error.code === qrec.noData) {
// found no row
} else {
// something else is wrong;
}
});
Similar considerations are made when choosing method many vs manyOrNone (method any is a shorter alias for manyOrNone).
Type QueryResultError has a very friendly console output, just like all other types in the library, to give you a good idea of how to handle the situation.
In your catch handler for the query, just test for that error. Looking at pg-promise source code, a code of noData is 0. So just do something like this:
db.one('select * from users where loginName = $1', id).then(function(data) {
console.log(data);
resolve(data);
}).catch (function (e) {
if(e.code === 0){
resolve(null);
}
console.log('error: '+e);
reject(e);
});
So I want to search for items in my database using mongoose .find() function.
In my router I have this code to get certain items from the url.
For example;
mydomainname.com/market?type=1&name=hi&stats=123
...?type=123&name=&...
var type = req.query.type;
var name= req.query.name;
var stats= req.query.stats;
Model.find({type: type, name: name, stats: stats})
.exec(function(err, model){
if(err){
console.log("error")
}else{
res.render('*jade*', {models: JSON.stringify(model)})
}})
This works fine, but when there is no query value in the url(as seen above) the query value will be set to ''. Which then sorts away every item I have on my database because there is none with exmaple name = '';
I have search around but I have not find any help so if any would be able to give me tip I would be grateful!
You could create your find() query object based on the value of the request query parameters. The following example checks for the name field if it has an empty string value, remove the property from the query and then use the final query object as your find() filter:
var q = req.query;
if (q.name === '') {
delete q.name;
}
// carry out further checks
Model.find(q)
.exec(function(err, model){
if(err){
console.log("error");
}else{
res.render('*jade*', {models: JSON.stringify(model)});
}
})
Try this
var q = req.query;
var data ={};
if (q.name !=null) {
data.name = q.name;
}
else if (q.type !=null){
data.type = q.type;
}
else if (q.stats !=null){
data.stats = q.stats;
}
else{
data={};
}
Model.find(data)
.exec(function(err, model){
if(err){
console.log("error");
}else{
res.render('*jade*', {models: JSON.stringify(model)});
}
})
I am trying to save a new Document (user) in my MongoDb and I use callback. The code runs and goes until save the user, but after that I get an error.So I can save user. I have the following code:
function saveUser(userName, socialMediaType, socialMediaID, setDocNumber, callback){
var user;
if(socialMediaType == "fbUID"){
user = new users({
userName: userName,
userEmail: 'userEmail',
teams:[],
fbUID : socialMediaID
});
}else
if(socialMediaType =="google"){
//do the same
}
var query = {}
query["'"+ socialMediaType +"'" ] = socialMediaID
users.findOne(query, function(err, userFound){
if (err) { // err in query
log.d("Error in query FoundUser", err)
log.d("User Found", userFound)
}else
if(userFound == undefined){ //if user does not exist
user.save(function(err, user){
if(err) return console.error(err);
log.d("user saved", user);
currentSession = sessionOBJ.login(user._id, socialMediaID);
callback(currentSession,"created")
});
}else{
currentSession = sessionOBJ.login(userFound._id, socialMediaID);
callback(currentSession,"logged")
}
});
}
I call the function above through this code:
f(fbUID !== undefined){
userModelOBJ.saveUser(userName,"fbUID", fbUID, function(currentSession, status) {
res.send({"status":status,
"sessionID": currentSession.sessionID,
"expires" : currentSession.date});
});
I am getting this error :
The error is in the line :
callback(currentSession,"created")
What could be the problem?
I already did many researchers but this is a specific case.
Your saveUser() call is missing the setDocNumber argument. It looks like you're not using it in your code though, so you might be able to safely remove it. If you are using it somewhere else (that you haven't shown) then you need to do some argument checking at the top of saveUser() to support optional arguments.
I'm new to Node and CouchDb and I'm trying to get my hands on it.
I'm struggling to make a piece of code to work.
I would like to create a table users, insert a new user and 'at the same time' getting another user.
I'm getting this error when starting up node app.js :
antoine#ubuntu:~/projects/couchDb$ node app.js
Database users exists.
{"error":"conflict","reason":"Document update conflict."}
Leaving saveDoc
events.js:48
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1107:15)
at Socket.onend (http.js:1188:27)
at TCP.onread (net.js:369:26)
And here is my very code, is there something wrong?
(When I remove the getDoc function the error goes away)
I'm using couchDB 1.0.1 and node 0.6.12
The jdoe4 and jdoe documents are already present in the users database.
var dbHost = "127.0.0.1";
var dbPort = 5984;
var dbName = 'users';
var couchdb = require('felix-couchdb');
var client = couchdb.createClient(dbPort, dbHost);
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
var db = client.db(dbName);
db.exists(function(err, exists) {
if (!exists) {
db.create();
console.log('Database ' + dbName + ' created.');
} else {
console.log('Database ' + dbName + ' exists.');
}
db.saveDoc('jdoe4', user, function(err, doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.getDoc('jdoe', function(err,doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
It seems to be a library problem => Github Issue Socket Hangout
Look here if you dont know which library fit more your needs.
I quickly realized that felix-couchdb is not compatible with node 8 (I know you're not using version 8, but you will someday), so I switched to nano couchdb and here's the following code:
It will check if the db is created
It will insert only if the key given is unique
It will get the user with a key
var couchdb = require('nano')('http://localhost:5984')
, dbName = 'users'
, db = couchdb.use(dbName)
;
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
couchdb.db.create(dbName, function(err, db_body) {
db.insert(user, 'jdoe4', function(err, doc, header) {
if( err) {
console.log('Cannot save user');
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.get('jdoe', function(err, doc) {
if( err) {
console.log('Cannot get user');
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
One thing worth noting is that, while this will get them at the "same time," it's still making 3 requests to the db, 1 to check if it exists, 1 to insert (or not), 1 to get.