首页 > 解决方案 > 尝试使用redis将数组转换为猫鼬文档时,Document()的参数obj必须是一个对象

问题描述

我使用 redis 来缓存我的查询。它与对象一起工作正常,但当我得到数组时却不行。它给了我一个错误**“Document()的参数“obj”必须是一个对象,有孩子”,**。计数查询也会发生这种情况。这是我的代码:

const mongoose = require("mongoose");
const redis = require("redis");
const util = require("util");

const client = redis.createClient(process.env.REDIS_URL);
client.hget = util.promisify(client.hget);

const exec = mongoose.Query.prototype.exec;

mongoose.Query.prototype.cache = async function (options = {}) {
    this.useCache = true;
    this.hashKey = JSON.stringify(options.key || "");
    this.time = JSON.stringify(options.time || 36000);

    return this;
};

mongoose.Query.prototype.exec = async function () {
    if (!this.useCache) {
        return exec.apply(this, arguments);
    }
    const key = JSON.stringify(
        Object.assign({}, this.getQuery(), {
            collection: this.mongooseCollection.name,
        })
    );
    // client.flushdb(function (err, succeeded) {
    //  console.log(succeeded); // will be true if successfull
    // });

    const cacheValue = await client.hget(this.hashKey, key);

    if (cacheValue) {
        const doc = JSON.parse(cacheValue);
        /*
        this.model refers to the Class of the corresponding Mongoose Model of the query being executed, example: User,Blog
        this function must return a Promise of Mongoose model objects due to the nature of the mongoose model object having other
        functions attached once is created ( validate,set,get etc)
      */

        console.log("Response from Redis");
        console.log(doc);
        console.log(Array.isArray(doc));

        return Array.isArray(doc)
            ? doc.map((d) => new this.model(d))
            : new this.model(doc);
    }

    //await the results of the query once executed,  with any arguments that were passed on.

    const result = await exec.apply(this, arguments);

    client.hset(this.hashKey, key, JSON.stringify(result));
    client.expire(this.hashKey, this.time);
    console.log("Response from MongoDB");

    return result;
};

module.exports = {
    clearHash(hashKey) {
        client.del(JSON.stringify(hashKey));
    },
};

redis 中的数据 - [ 'kids', 'men', 'women' ] 查询 - const collectionType = await Product.find() .distinct("collectionType") .cache({ key: "COLLECTION_TYPE" });

谁能告诉我我做错了什么?

标签: node.jsmongodbmongooseredis

解决方案


我已经通过直接返回文档及其工作正常来解决。如果我直接返回文档然后仅从redis发送数据,不确定这是否是正确的方法


推荐阅读