how to get all users in redis - node.js

I have the following code .
var redis = require("redis"),
client = redis.createClient();
user_rahul = {
username: 'rahul'
};
user_namita = {
username: 'namita'
};
client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
client.hgetall("users" , function(err, user) {
console.log(user);
});
I want to get all the users list how i can get all users list this what i tried but its not working.

You are setting the users in their own hash, so when you do hgetall users, you are trying to get all the members of the users hash. You should do:
var redis = require("redis"),
client = redis.createClient();
user_rahul = {
username: 'rahul'
};
user_namita = {
username: 'namita'
};
client.hset('users', user_rahul, 'Another Value, Pass Maybe?');
client.hset('users', user_namita, 'Another Value, Pass Maybe?');
var username = "rahul"; // From a POST perhaps
client.hgetall("users" , function(err, user) {
console.log(user);
});
You should consider using a list instead, if you dont need any data in the second hash value

How about this
var flow = require('flow'); //for async calls
var redis = require("redis").createClient();
function AddUser(user,callback){
flow.exec(
function(){
//AI for Keep unique
redis.incr('nextUserId',this);
},
function(err,userId){
if(err) throw err;
this.userId = userId;
redis.lpush('users',userId,this.MULTI());
redis.hmset('user:'+userId+':profile',user,MULTI());
},
function(results){
results.forEach(function(result){
if(result[0]) throw result[0];
});
callback(this.userId);
}
);
}
user_rahul = {username: 'rahul'};
user_namita = {username: 'namita'};
//Add user
AddUser(user_rahul,function(userId){
console.log('user Rahul Id' + userId);
});
AddUser(user_namita,function(userId){
console.log('user Namita Id' + userId);
});
//users
function Users(callback){
var users = [];
flow.exec(
function(){
redis.lrange('users',0,-1,this);
},
function(err,userIds){
if(err) throw err;
flow.serialForEach(userIds,function(userId){
redis.hgetall('user:'+userId+':profile',this);
},
function(err,val){
if(err) throw err;
users.push(val);
},
function(){
callback(users);
});
}
);
}
//call
Users(function(users){
console.log(users);
});

For Single User
function getUser(userId,callback){
redis.hgetall('user:'+ userId +':profile',function(err,profile){
if(err) throw err;
callback(profile);
});
}
getUser(1,function(profile){
console.log(profile);
});

Related

Error: Socket hang up cannot read property result[2]

I've tried to insert the data from webform to neo4j database but my record has been inserted but at the same time i got this error socket hang up.
And Match query doesn't work help out for this problem
app.post('/insert',function (req,res){
var email = req.body['email'];
var password = req.body['password'];
var query = [
'CREATE (user:test {newUser})'
// 'RETURN user'
]
var params = {
newUser: {
email: email,
password: password,
}
};
db.cypher({
query: query,
params: params
},
function(err,user){
if(err) console.log(err) ;
console.log(user);
res.send("Record has been Inserted ");
});
})
app.get('/json', function(req,res){
db.cypher({
query: 'MATCH (user:test {email: {email}}) RETURN user'
}, function (err, results) {
if (err) console.log(err);
var result = results[2];
if (!result) {
console.log('No user found.');
} else {
var user = result['user'];
console.log(JSON.stringify(user, null, 4));
}
});
})

How to return a value from a mysql SELECT query in node.js

I'm still very new to Node.js, and i'm trying to understand how callbacks work.
So, here is my problem :
I should've put more code :
POST :
app.post('/register', function(req, res) {
//get data from the request
var data = {
username: req.body.username,
email: req.body.email,
password: req.body.password
};
function fetchID(callback) {
connection.query('SELECT id_user FROM USERS WHERE username = ?', data.username, function(err, rows) {
if (err) {
callback(err, null);
} else
callback(null, rows[0].id_user);
});
}
var user_id;
fetchID(function(err, content) {
if (err) {
console.log(err);
return next("Mysql error, check your query");
} else {
user_id = content;
console.log(user_id); //undefined
}
});
console.log(user_id); //undefined
var payload = {
iss: req.hostname,
sub: user_id
}
console.log(payload.sub); //correct id
})
GET :
app.get('/todos', function(req, res) {
if (!req.headers.authorization) {
return res.status(401).send({
message: 'You are not authorized !'
});
}
var token = req.headers.authorization.split(' ')[1];
var payload = jwt.decode(token, "shhh..");
//additional level of security
console.log('sub id is : ' + payload.sub); //undefined
if (!payload.sub) {
return res.status(401).send({
message: 'Authentication failed !'
});
}
})
I commented each console.log to be more clear. I need to get the correct id when i check for if (!payload.sub) in app.get()
Your two functions should be something like -
function fetchID(data, callback) {
connection.query('SELECT id_user FROM USERS WHERE username = ?', data.username, function(err, rows) {
if (err) {
callback(err, null);
} else
callback(null, rows[0].id_user);
});
}
and then
var user_id;
fetchID(data, function(err, content) {
if (err) {
console.log(err);
// Do something with your error...
} else {
user_id = content;
}
});
Here in the callback function, the returned variable content will hold the value for user_id.
EDIT
I have not solved the exact problem as you had described above.
But in following example, I have shown that, the callback mechanism is working -
First (Table creation and insert some dummy data)-
use test;
create table users (id int(11) primary key,username varchar(100));
insert into users values(1, "John");
insert into users values(2, "Sham");
Now I have made your post method as get and tested in browser.
Following is the full class tested in my localhost -
var application_root = __dirname,
express = require("express"),
mysql = require('mysql');
var app = express();
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'admin',
database: "test"
});
app.get('/getuser', function(req, res) {
//get data from the request
var data = {
username: req.query.username
};
function fetchID(data, callback) {
connection.query('SELECT id FROM users WHERE username = ?',
data.username, function(err, rows) {
if (err) {
callback(err, null);
} else
callback(null, rows[0].id);
});
}
var user_id;
fetchID(data, function(err, content) {
if (err) {
console.log(err);
res.send(err);
// Do something with your error...
} else {
user_id = content;
console.log(user_id);
res.send("user id is -" + user_id);
}
});
})
app.listen(1212);
Now these requests will produce this output -
http://127.0.0.1:1212/getuser?username=john => user id is -1 and
http://127.0.0.1:1212/getuser?username=sham => user id is -2
Hope this code example will help you to understand the callback in node.js.
Thanks

Node Async not executing the db function

I am sending a post request from a form but async.waterfall() doesn't execute the mongoose's User.find() function to fetch users from the database and as a result the post request's status in the network inspector is pending as res.send() is not being called.
exports.createUser = function(req,res){
var email1 = req.body.mail.toString();
var password = req.body.password.toString();
async.waterfall([
function(callback) {
// verify user in the db
User.find({email:email1},function(err,data){
if (err){
res.send(404);
return callback(err);
}
// user is found
if (data.length != 0){
res.send(404);
return callback(new Error("User Found"));
}
callback();
});
},
// generate salt password
function(callback) {
bcrypt.genSalt(SALT_WORK_FACTOR,function(err,salt){
if (err) return callback(err);
bcrypt.hash(password,salt,function(err,hash){
if (err) return callback(err);
return callback(null,hash);
});
});
},
//generate random string
function(hash,callback){
crypto.randomBytes(48,function(err,buf){
if (err) return callback(err);
var randomString = buf.toString('hex');
return callback(null,hash,randomString);
});
},
// save them in the mongoDb using mongoose
function(hash,randomString,callback){
var userModel = new User;
userModel.email = email1;
userModel.password = hash;
userModel.verificationId = randomString;
userModel.save();
callback(null,'done');
}
],function(err){
if (err){
console.log(err);
res.send(404);
} else{
console.log("done");
res.send("200");
}
});
}
Here is my app.js file using express
// render the registration page
app.get('/users/create',register.renderUserPage);
app.post('/users/create',function(req,res){
register.createUser(req,res);
});
Here is the Db.js file which connects to mongoDb using mongoose
console.log("connection succeeded");
var UserSchema = new Schema ({
email: {type:String ,require : true ,index : {unique : true}} ,
password:{ type : String ,required: true} ,
verificationId:{type:String, required:true,index:true}
});
UserSchema.plugin(ttl,{ttl:90000000});
module.exports = mongoose.model('User',UserSchema);

NodeJs + Postgres synchronus connection to Database to populate variable

I'm using nodeJs express 3 framework with postgreSQL, I'm using the script below to look for a username in DB and populate a variable so I can pass it to my view.
Here is my script :
app.js
var app = express();
app.use(express.bodyParser());
......
function fncCheckUsernameAvailability(vstrUsername){
var pg = require("pg");
var client = new pg.Client({user: 'xxx', password: 'xxxx', database: 'xxx', host: 'example.com'});
var response = "";
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query("SELECT username FROM users WHERE username ='"+vstrUsername+"'", function(err, result) {
if(err) {
return console.error('error running query', err);
}
if(result.rows[0] == undefined){
//console.log("Username available");
response = "Username available";//Populating The variable here
}else{
//console.log("Username already taken");
response = "Username already taken";//Populating The variable here
}
client.end();
});
});
return response;
}
app.post("/Signup", function(req, res){
var username = req.body.username;
var Response = fncCheckUsernameAvailability(username);
console.log(Response);
}
The response variable is allways "undefined", so how can I make that script waiting until the DB checking is done to populate the "response" variable?
You cannot place return values into asynchronous functions. You would instead need to use a callback, and this is what your code might look like:
function fncCheckUsernameAvailability(vstrUsername, callback) {
client.connect(function(err) {
if (err) {
callback(err, null);
return;
}
client.query("SELECT username FROM users WHERE username ='" + vstrUsername + "'", function (err, result) {
client.end();
if (err) {
callback(err, null);
return;
}
if (result.rows[0] == undefined) callback(null, 'Username available.');
else callback(null, 'Username taken.');
});
});
};
You would use the function like this:
app.post("/Signup", function(req, res) {
var username = req.body.username;
fncCheckUsernameAvailability(username, function(err, result) {
console.log(result);
});
});

function is not returning data

I have the following code
var redis = require("redis"),
client = redis.createClient();
var getuser = function(username) {
var userhash={};
client.hgetall("users."+username, function(err, user) {
userhash=user;
});
return userhash;
};
user_rahul = {
username: 'rahul',
queueno: 1,
sessionId: '6604353811126202'
};
user_namita = {
username: 'namita',
sessionId:'2'
};
client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
var user1=getuser(username);
console.log(user1);
client.hgetall("users." + username, function(err, user) {
console.log(user);
});
i have created a getuser function to return the value of particular username in userhash but it is not returning please help in finding why it is not returning .
what should i do to get the value return ?
You're mixing sync and async patterns when you make an async call in your sync getUser function. You need to make your getUser function async - e.g:
var redis = require("redis"),
client = redis.createClient();
var getuser = function(username, cb) {
client.hgetall("users."+username, cb);
};
user_rahul = {
username: 'rahul',
queueno: 1,
sessionId: '6604353811126202'
};
user_namita = {
username: 'namita',
sessionId:'2'
};
client.hmset('users.rahul', user_rahul);
client.hmset('users.namita', user_namita);
var username = "rahul"; // From a POST perhaps
getuser(username, function(err, res){
console.log(res);
});
client.hgetall("users." + username, function(err, user) {
console.log(user);
});

Resources