node.js - 尝试使用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" });
谁能告诉我我做错了什么?
解决方案
我已经通过直接返回文档及其工作正常来解决。如果我直接返回文档然后仅从redis发送数据,不确定这是否是正确的方法
推荐阅读
- apache-kafka - 如何设置 Kafka 消费者配置以从现在开始消费消息?
- amazon-s3 - 您的 Amazon Music 市场没有为此设备正确配置
- node.js - REST API 的 Flash 消息
- ruby-on-rails - FactoryBot 如何为相互关联的模型创建工厂
- git - 我应该在开发完全完成之前合并 dev 和 master 分支吗?
- c# - 线程池 ThreadStart 和 Finished 问题 xamarin iOS
- python - 如何加快从 pandas.DataFrame .to_sql 插入
- angular - 无法读取未定义的属性“findIndex”
- firebase - Firebase 云函数 -@google-cloud/storage 初始化
- sql - 从 SQL Server 中的两个不同服务器获取数据