【问题标题】:Parameter obj to Document() must be an object when trying to convert array to mongoose document with redis尝试使用 redis 将数组转换为猫鼬文档时,Document() 的参数 obj 必须是一个对象
【发布时间】:2021-08-03 18:27:40
【问题描述】:

我使用 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.js mongodb mongoose redis


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 2021-09-08
      • 2022-12-20
      • 1970-01-01
      • 2015-03-29
      • 2019-06-16
      相关资源
      最近更新 更多