簡體   English   中英

MongoError:無條件獲取所有數據時池被破壞

[英]MongoError: pool destroyed when fetching all data without conditions

我是 mongoDb 的新手,因為我試圖從不同的集合中查詢,為了做到這一點,當我從類別集合中獲取數據時,我的意思是當我運行 select * 從集合中拋出錯誤時,MongoError:池被破壞。

根據我的理解,這是因為一些 find({}) 正在創建一個池並且正在被銷毀。

我在 model 中使用的代碼如下,

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 它會引發池錯誤。

我在 controller 中編寫的代碼如下,

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(); call 將在讀取結果之前執行,因此可能會產生錯誤。

完成對結果的迭代后,需要進行close調用。

除此之外,您可能不應該像這樣在請求處理程序中創建客戶端實例。 客戶端實例的創建成本很高(它們必須與部署中的所有服務器通信,然后才能真正執行查詢),並且通常應該按正在運行的進程而不是按請求創建。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM