我是mongoDb的新手,因为我正在尝试从其他集合中查询,因此,当我从类别集合中获取数据时,我的意思是当我运行select * from collection时会引发错误,MongoError:池毁了。
据我了解,这是因为某些find({})正在创建一个池,并且该池已被销毁。
我在内部模型中使用的代码如下,
const MongoClient = require('mongodb').MongoClient;
const dbConfig = require('../configurations/database.config.js');
export const getAllCategoriesApi = (req, res, next) => {
return new Promise((resolve, reject ) => {
let finalCategory = []
const client = new MongoClient(dbConfig.url, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db(dbConfig.db).collection("categories");
debugger
if (err) throw err;
let query = { CAT_PARENT: { $eq: '0' } };
collection.find(query).toArray(function(err, data) {
if(err) return next(err);
finalCategory.push(data);
resolve(finalCategory);
// db.close();
});
client.close();
});
});
}
[当我在这里发现时是在使用中
让查询= {CAT_PARENT:{$ eq:'0'}};collection.find(query).toArray(function(err,data){})
当我使用find(query)时,它返回数据,但是使用{}或$ gte / gt,它会抛出Pool错误。
我在控制器中编写的代码在下面,
import { getAllCategoriesListApi } from '../models/fetchAllCategory';
const redis = require("redis");
const client = redis.createClient(process.env.REDIS_PORT);
export const getAllCategoriesListData = (req, res, next, query) => {
// Try fetching the result from Redis first in case we have it cached
return client.get(`allstorescategory:${query}`, (err, result) => {
// If that key exist in Redis store
if (false) {
res.send(result)
} else {
// Key does not exist in Redis store
getAllCategoriesListApi(req, res, next).then( function ( data ) {
const responseJSON = data;
// Save the Wikipedia API response in Redis store
client.setex(`allstorescategory:${query}`, 3600, JSON.stringify({ source: 'Redis Cache', responseJSON }));
res.send(responseJSON)
}).catch(function (err) {
console.log(err)
})
}
});
}
谁能告诉我我在这里犯了什么错误。如何解决池问题。预先感谢您。
我假设toArray
是异步的(即,它在结果变为可用时(即从网络读取)调用传入的回调。)>
如果为真,则将在读取结果之前执行client.close();
调用,因此可能会产生错误。