0

I tried node.js crud operation using mongodb and also stored in redis cache. First time I tried to run get method to get data from db and second time I run the get method. It got data from cache but I tried to delete the data in the table and another time to run get method it is not showing data.It is showing empty data. But data is stored in redis cache. how can I solve this issue?

cache.js

// var asyncRedis = require("async-redis")

// var myCache = asyncRedis.createClient()
var redis = require('redis');

const client = redis.createClient()

client.on('connect', function () {
    console.log('Redis client connected');
});

client.on('error', function (err) {
    console.log('Something went wrong ' + err);
});



var value;
var todayEnd = new Date().setHours(23, 59, 59, 999);







function  Get_Value()
{
    client.get('products', function(err,results) {
        value = JSON.parse(results);

    })
    return value
}

function Set_Value(products)
{
    client.set('products', JSON.stringify(products))
    client.expireat('products', parseInt(todayEnd/1000));


}

exports.get_value = Get_Value;

exports.set_value = Set_Value;

routes.py

data = cache.get_value()
      console.log(data)
      if (data) {
        console.log("GET")
        res.send(data)
      }
      else {
        console.log("SET")
        const r = await db.collection('Ecommerce').find().toArray();
        res.send(r)
        data = cache.set_value(r)
      }
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
smith hari
  • 437
  • 1
  • 11
  • 22

1 Answers1

0

hari,

Your Get_Value looks a little odd to me. The Redis get will be executed asynchronously. So when you place the return value statement outside the callback, it will return right away, value is still undefined.

The easiest way to solve this would be to call Get_Value with a callback to continue when redis GET returns.

function  Get_Value(callback) {
    client.get('products', function(err,results) {
        let value = JSON.parse(results);
>>      callback(value);
    });
}

You would use it like that:

Get_Value(function(value) {
    console.log("products: " + value);
}

An other option would be to use the Promise API from Node Redis (see docs here: https://github.com/NodeRedis/node_redis)

Does this help?

Konstantin A. Magg
  • 1,106
  • 9
  • 19