Fogarasi Norbert
Fogarasi Norbert

Reputation: 672

Insert array into redis from NodeJS

I have an array which I fill up in a for like this:

var obj = [];
for(i = 0; i < data.bids.length; i += 1) {
    obj.push(JSON.parse(data.bids[i][0]));
}

After that I verify if the array contains the desired values (it contains):

console.log("Array after the for: \n");
console.log(obj);

I try to save this under a redis key, but the reply is undefined

client.set('order-book:buy:bitstamp', obj, function(err, reply) {
    console.log(reply);
});

I've also tried with rpush, but no luck.
What could be the problem?

Upvotes: 7

Views: 16196

Answers (1)

Tomislav
Tomislav

Reputation: 752

You can check here which types are compatible as redis values data-types-intro.

If you need to save array of objects in redis, the only way to do this is by using JSON.stringify(obj). So in your example it would look something like:

const redisValue = JSON.stringify(obj);
client.set('order-book:buy:bitstamp', redisValue, function(err, reply) {
    console.log(reply);
});

When reading data from redis you can easily use JSON.parse(redisResponse).

Upvotes: 16

Related Questions