I have just discovered how cool node js is and was looking at options for persisting. I saw that you could use redis-client to store data in redis and I have been able to store data ok, like so:
var redis = require('redis-client');
var r = redis.createClient();
var messege = {'name' => 'John Smith'};
var type = "Contact";
r.stream.on( 'connect', function() {
r.incr( 'id' , function( err, id ) {
r.set( type+':'+id, JSON.stringify(messege), function() {
sys.puts("Saved to redis");
});
});
});
This store a key with a json string as the value. I am however trying to retrieve all the keys from redis and loop around them. I am having trouble figuring out the way to do this, could anyone point me in the right direction?
Cheers
Eef
To get keys from redis, you should use the .keys parameter. The first parameter that you pass is a 'filter' and .keys will return any items matching the filter.
For example r.keys('*', ...) will return all of the keys in redis as an array.
Here's the documentation on this command: http://redis.io/commands/keys
To loop through them, you can just do a simple for in as follows:
r.keys('*', function (keys) {
for (key in keys) {
console.log(key);
}
});
Related
Is there any way to update and push simultaneously?
I want to update a key2 in my object and simultaneously push unique keys under timeline in a single request ref().child('object').update({...}).
object
key1:
key2: // update
key3:
timeline:
-LNIkVNlJDO75Bv4: // push
...
Is it even possible or one ought to make two calls in such cases?
Calling push() with no arguments will return immediately (without saving to the database), providing you with a unique Reference. This gives you the opportunity to create unique keys without accessing the database.
As an example, to obtain a unique push key, you can do some something like:
var timelineRef = firebase.database().ref('object/timeline');
var newTimelineRef = timelineRef.push();
var newTimelineKey = newTimelineRef.key;
With this, you can then perform a multi-level update which makes use of the new key:
var objectRef = firebase.database().ref('object');
var updateData = {};
updateData['object/key2'] = { key: 'value' };
updateData['object/timeline/' + newTimelineKey] = { key: 'value' };
objectRef.update(updateData, function(error) {
if (!error) {
console.log('Data updated');
}
});
i have a simple question and i have read a lot of same issues here, but these are not exact the same or doesn't work for me :-(
I have a REST function called "addevent". The function gets a json input (req) and iterate through the json array to get some IDs to store them in an extra Array. That works perfect!
After that, the function should search in a mongodb for every single id and store some extra informations from this ID (e.g. the stored URL of this ID). With "console.log(result.link)" it works again perfect. But my problem is that, that i need to store this link in an extra Array (urlArray).
So how can i save the result of collection.findone(). I read something about, that findone() doesn't return a document, but a cursor? what does that mean? How do i have to handle that in my case?
That's the code:
exports.addevent = function(req, res) {
var ids = req.body;
var pArray = new Array();
var urlArray = new Array();
var eventName = ids.name;
for(var i in ids.photos) {
photoArray.push(ids.photos[i]);
var id = ids.photos[i]._id;
var collection = db.get().collection('photos');
collection.findOne({'_id':new mongo.ObjectID(id)},function(err, result) {
console.log(result.link);
}
)
}
Many thanks!
-------------------- Update --------------------
Ok, i think that has something to do with the asynch Callbacks. I found an article, but i don't know how to implement it in my case.
http://tobyho.com/2011/11/02/callbacks-in-loops/
And something about "promises" in javascript.
You can save the result of your search doing something like:
var foundPhoto = collection.find({_id':new mongo.ObjectID(id)}, function(err, photo){
if(!err){
return photo;
} else {
console.log(err)
return null;
}
});
This way you get the return statement of your query in the "photo" variable.
Firebase - How to get list of objects without using AngularFire
I'm using typescript, angular2 and firebase.
I'm not using angularfire. I want to extract the data using their Api
My firebase url is /profiles
This is the list of profiles I'm looking to extract:
Thanks.
Use a simple value event and re-assign the array every time the value changes.
JSBin Demo.
var ref = new Firebase('https://so-demo.firebaseio-demo.com/items');
ref.on('value', (snap) => {
// snap.val() comes back as an object with keys
// these keys need to be come "private" properties
let data = snap.val();
let dataWithKeys = Object.keys(data).map((key) => {
var obj = data[key];
obj._key = key;
return obj;
});
console.log(dataWithKeys); // This is a synchronized array
});
I'm trying to store an object in my chrome extension containing other objects using chrome.storage - but am having trouble initializing it and properly fetching it using chrome.storage.sync.get. I understand that I'm supposed to get objects in the form of chrome.storage.sync.get(key: "value", function(obj) {} - the issue is I'm not sure how to
Initialize the object the first time with get
Properly update my object with set
I have the following code to create the object and add the data I need.
allData = {};
currentData = {some: "data", goes: "here"};
allData[Object.keys(allData).length] = currentData;
This will correctly give me an object with it's first key (0) set to currentData. (Object: {0: {some: "data", goes: "here"}}) Working as intended, and allData[Object.keys(allData).length] = currentData; will properly push whatever currentData is at the time into my Object later on.
But how do I properly store this permanently in chrome.storage? chrome.storage.sync.get("allData", function(datas) {}) fails to create an empty allData variable, as does allData: {}, allData = {}, and a variety of different things that return either undefined or another error. How do I properly initialize an empty object and store it in chrome.storage? Or am I going about this all wrong and need to break it down into associative arrays in order for it to work?
I essentially need that small block of working code above to be stored permanently with chrome.storage so I can work with it as needed.
You first need to set the data inside the storage:
allData = {};
currentData = {some: "data", goes: "here"};
// to initialize the all data using the storage
chrome.storage.sync.get('allData', function(data) {
// check if data exists.
if (data) {
allData = data;
} else {
allData[Object.keys(allData).length] = currentData;
}
});
// Save it using the Chrome extension storage API.
chrome.storage.sync.set({'allData': allData}, function() {
// Notify that we saved.
message('Settings saved');
});
After that you should be able to access the data using the chrome.storage.sync.get('allData', function(){ ... }) interface.
You can easily do this with the new JavaScript (ECMAScript 6), have a look into Enhanced Object Properties:
var currentData = {some: "data", goes: "here"};
chrome.storage.local.set({allData: currentData });
In the old way, was something like this:
var obj = {};
var key = "auth";
obj[key] += "auth";
obj[key] = JSON.stringify({someKey: someValue});
I am trying to parse a multilevel json file, create a model and then add that model to a backbone collection but i can't seem to figure out how to push the model to the collection. This should be a pretty easy problem to solve, i just can't seem to figure it out. Thanks in advance for your help. Below is my model and collection code:
var Performer = Backbone.Model.extend({
defaults: {
name: null,
top5 : [],
bottom5 : []
},
initialize: function(){
console.log("==> NEW Performer");
// you can add event handlers here...
}
});
var Performers = Backbone.Collection.extend({
url:'../json_samples/performers.json',
model:Performer,
parse : function(data) {
// 'data' contains the raw JSON object
console.log("performer collection - "+data.response.success);
if(data.response.success)
{
_.each(data.result.performers, function(item,key,list){
console.log("running for "+key);
var tmpObject = {};
tmpObject.name = key;
tmpObject.top5 = item.top5;
tmpObject.bottom5 = item.bottom5;
var tmpModel = new Performer(tmpObject);
this.models.push(tmpModel);
});
}
else
{
console.log("Failed to load performers");
}
}
});
As has been said in comments to your question, parse() is not intended to be used this way. If data.results.performers was an Array, all you would have to do is returning it. In your case the code will be slightly different.
var Performers = Backbone.Collection.extend({
...
parse: function(resp, options) {
return _.map(resp.result.performers, function(item, key) {
return _.extend(item, {name: key});
});
}
...
});
On the advice side, if you have the chance to change the API server-side, you'd probably be better off treating collections of objects as arrays and not as objects. Even if it is sometimes convenient to access an object by some ad-hoc key, the data really is an array.
You'll be able to transform it later when you need performers-by-name with a function like underscore's IndexBy