【问题标题】:how to use redis in mongoose toJSON properly?如何在 mongoose toJSON 中正确使用 redis?
【发布时间】:2021-07-19 08:22:01
【问题描述】:

我想检查redis中是否存在coinObject.coinid,如果存在,我想将在线值添加到我的对象中,如果它为null,我想将coinObject['online']设置为0。

但是这个 cod 根本不起作用,当我尝试从 client.get 方法中添加一些虚拟数据时,它可以正常工作,它会正确返回,但我想根据每个对象的 coinid 属性来做到这一点,谢谢

  coinScheme.methods.toJSON =  function (){
        const coin = this
        const coinObject = coin.toObject()
        
       client.get(coinObject.coinid,async (err,reply)=>{
        
            if(err){
                console.log(err)
            }
            if(reply!=null){
                coinObject['online'] = reply
            }else{
                coinObject['online'] = 0
            }
           
        })
        return coinObject
    }

【问题讨论】:

    标签: node.js mongodb mongoose redis


    【解决方案1】:

    您正在同步函数 (toJSON) 内运行异步函数 (redis.get)。你可以使用 promise 或 callback 来解决它:

    // callback version
    // example: instance.toObjectAsync((err, coin) => console.log(err, coin))
    coinScheme.methods.toObjectAsync = function (callback) {
        const coin = this.toObject();
        client.get(coin.coinid, (err, reply) => {
            if (err) {
                return callback(err);
            }
    
            coin.online = reply === null ? 0 : reply;
            callback(null, coin);
        });
    };
    
    
    // promise version
    // example const coin = await instance.toObjectAsync();
    coinScheme.methods.toObjectAsync = async function () {
        const coin = this.toObject(),
            reply = await client.get(coin.coinid);
    
        coin.online = reply === null ? 0 : reply;
        return coin;
    };
    

    【讨论】:

      猜你喜欢
      • 2015-10-18
      • 2014-03-04
      • 2014-10-19
      • 1970-01-01
      • 2019-07-18
      • 2015-02-09
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多