I want to get data from Redis session with nodejs - but i can't get the inner values of the objects....
this is a simple router
router.get('/page-user', function (req, res) {
console.log(redis_model.prototype.getAll());
})
and here is the model
redis_model.prototype.getAll = function () {
client.keys('*', function (err, keys) {
if (err) return console.log(err);
for(var i = 0, len = keys.length; i < len; i++) {
console.log(keys[i]);
}
});
};
So i'm getting
users
id:users
session:php:cf5myWFkDNEPwiRLpi6M1P6LqX1UPFtj //object
user:{58}
I'm trying to fetch data from the session key and i'm getting Undefined , like this:
redis_model.prototype.getAll = function () {
client.keys('*', function (err, keys) {
if (err) return console.log(err);
console.log(keys['session']); // tried also keys.session
});
};
The part that i can't figure out is why i get Type String for all the keys - like here:
redis_model.prototype.getAll = function () {
client.keys('*', function (err, keys) {
if (err) return console.log(err);
console.log(typeof keys[i]); result : //string,string, string,string
});
};
I've tried HGETALL to get the keys as objects but i still get undefined :
redis_model.prototype.getAll = function () {
client.hgetall("session",function(data){console.log(data)});
};
Here is a screenshot of the redis db...
Client.keys("*",function(err,keys){})
This just returns all the keys present in the redisDB which are basically strings
Instead you can use
client.get('key',function(err,data){})
inorder to get the result as an object it should be stored as a hash i.e
client.hmset("session",{'php':'cf5myWFkDNEPwiRLpi6M1P6LqX1UPFtj'}
client.hgetall("session",function(data){console.log(data.php)})
the above code gives you the value assigned to php.
Got it....
redis_model.prototype.getAll = function () {
client.get('session:php:VfAPTh_NLpBrcq3VGHTC8uT7c-sF4bQd', function(err,
result){
var foo = (JSON.parse(result))['user'];
console.log( foo);
});
};
Related
I want to return "items" which is inside the for loop and also two additional functions."Items" is an object (I would not say variable) which consists of three array elements and that can be more depending on the situation. So I need to return "items" so I can access it outside and I can send it to the client using res.send(). If I send data inside the loop and function, it is returning with an error called "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client". I found the fix for it but on implementing them, nothing is happening. It is throwing me the same error. I was thinking to do it call back function but I am confused about how to use it in this case. Thanks in advance.
router.get("/send" , async (req, res) => {
try {
res.send("hello")
//await sendData()
getCollectionNames()
} catch (error) {
console.log(error);
}
function getCollectionNames(){
MongoClient.connect(url, function(err, db) {
var db = db.db('admin')
mongoose.connection.db.listCollections().toArray(function (err, names) {
for(let index = 0; index < names.length; index ++){
if (err) {
console.log(err);
}
let name = names[index].name
const collection = db.collection(name)
collection.find().toArray(function(err, items){
console.log(items)
})
}
});
})
}
})
I'm having problems handling a file list with async.map. When I pass a list larger than 2045 items, the code give a error. And there is no problem of the actual file because on manual runs and debuging with a few files it runs ok. Maybe its not the best code example that I have, but I'm in learning process
var insertInDb = function (err, book_data) {
count = function(book, cb){
book_db.findOne({identifier:book['identifier']}, function (err, docs) {
if (docs !== null) {
cb('Book exists already',null)
}else{
book_db.insert(book, function(err){
cb(err,book)
})
}
})
}
async.map(book_data, count)
};
var epubData = function (epub, nextEpub) {
var book_data = {};
epubParser.open(epub, function (err, epub_data) {
console.log(epub);
for (var i of epub_data.easy['simpleMeta']) { // <-- ERROR! TypeError: Cannot read property 'easy' of undefined
for (var attrname in i) {
if (attrname.indexOf('dc:') !== -1) {
book_data[attrname.split(':')[1]] = i[attrname];
book_data['file'] = epub;
}
}
}
nextEpub(err, book_data)
})
};
async.map(full_files_path.slice(0, 2045), epubData, insertInDb);
I am new to node and I have read the data from mongoDB successfully.
But I would like to store the whole data from the Collection into a variable in nodejs as I would like to use them in the index page.
I do not know how to store it.
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
seriescollection = db.collection('series');
});
var findseries = function (db, callback) {
var cursor = db.collection('series').find();
cursor.each(function (err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
//insertDocument(db, function () {});
findseries(db, function () {
db.close();
});
});
My sample JSON object in MongoDb is
{
"_id" : "b835225ba18",
"title" : "Name",
"imageurl" :"https://promotions.bellaliant.net/files/Images/TMN/Ballers-June2015.jpg",
"namespaceId" : "UNI890"
}
I would like to access all the fields and create a page based on the fields that I have stored. I need to access all the fields and that is my main goal.
This is a pet project I am working on a leisure time to learn MEAN stack a bit.
Thanks a lot for your help!!!!
There's a few issues with this code, but I think what you're looking for is the toArray method:
var findseries = function (db, callback) {
db.collection('series').find().toArray(function(err, allTheThings) {
// Do whatever with the array
// Spit them all out to console
console.log(allTheThings);
// Get the first one
allTheThings[0];
// Iterate over them
allTheThings.forEach(function(thing) {
// This is a single instance of thing
thing;
});
// Return them
callback(null, allTheThings);
}
}
More here: https://docs.mongodb.org/manual/reference/method/cursor.toArray/
And here: https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray
I'm new to Node.js. I'm trying to use the Node Redis plugin. What I'm trying to do is get the list of key/value pairs from a REDIS database. The asynchronous nature of Node is creating a challenge for me. When I try to print the key/value pairs, my array is empty. I think its because my query to the database hasn't completed yet.
The reason I'm creating an array first instead of just printing out the key/value pairs, is because I want to sort the results alphabetically by either key or value. Currently, I"m trying the following:
redisClient.on('connect', function() {
var pairs = [];
redisClient.keys('*', function (err, keys) {
if (err) { return console.log(err); }
for(var i = 0, len = keys.length; i < len; i++) {
(function(key) {
redisClient.get(key, function(err, v) {
pairs.push({ key: key, value: v });
});
})(keys[i]);
}
});
// List of key/value pairs ordered alphabetically
console.log(pairs);
});
Can someone tell me how to get beyond this issue? Thank you
You are right in your assertion that when console.log is executed, nothing has happened yet. To deal with this kind of problem in Node.js, some people like to use modules like async and others prefer to use promises (a popular library for promises is Q).
Here is a solution using async.
var async = require('async');
redisClient.on('connect', function() {
redisClient.keys('*', function (err, keys) {
if (err) { return console.log(err); }
async.map(keys, function(key, callback) {
redisClient.get(key, function(err, value) {
callback(null, {key: key, value: value});
});
}, function(err, pairs) {
console.log(pairs);
});
});
});
async just happens to have a map function that takes an array, applies a function asynchronously to each elements and creates an array with the results.
You need to use recursion:
do = function(i, data, callback){
// if the end is reached, call the callback
if(data.length === i+1)
return callback()
obj = data[i]
redisClient.get(key, function(err, v) {
pairs.push({ key: key, value: v });
i++;
// call do with the next object
do(i, data, callback)
});
}
// Redis...
do(0, keys, function(){
// List of key/value pairs ordered alphabetically
console.log(pairs);
});
I have node.js router for mongodb mapreduce:
app.get('/api/facets/:collection/:groupby', function(req, res) {
var collection = db.collection(req.params.collection);
var groupby = req.params.groupby;
var map = function() {
if (!this.region) {
return;
}
for (index in this.region) {
emit(this.region[index], 1);
}
}
var reduce = function(previous, current) {
var count = 0;
for (index in current) {
count += current[index];
}
return count;
}
var options = {out: groupby + '_facets'};
collection.mapReduce(map, reduce, options, function (err, collection) {
collection.find(function (err, cursor) {
cursor.toArray(function (err, results) {
res.send(results);
});
})
})
});
This works good. But I want to use my groupby param. When I try to do something like this:
var map = function() {
if (!this[groupby]) {
return;
}
for (index in this[groupby]) {
emit(this[groupby][index], 1);
}
}
I receive TypeError: Cannot call method 'find' of undefined. Is there any way to create such dynamic mapreduce function?
Thanks.
Edited:
Wow! I do it myself. Just pass scope param to mapreduce argument like so scope:{keys: groupby} and then I was able to do var key = this[keys] inside map function and use key variable instead this.region. Great!
Wow! I solved it myself. I just passed a scope param to the mapreduce argument.
scope:{keys: groupby}
Then I was able to do
var key = this[keys]
inside map function and use key variable instead of this.region. Great!