Git Product home page Git Product logo

Comments (17)

Sigmaxii avatar Sigmaxii commented on June 24, 2024 1

Other than the error, what are the logs its printing? Like, is it printing any of the above logs mentioned in the code? Also, is it working by just doing await mongoose.connect()?

the console.logs are printing that its connecting succesfully, and then the error pops, after a few seconds

from mongoose.

ghost-dev-gr avatar ghost-dev-gr commented on June 24, 2024 1

Does the connection appear on the dashboard of mongoose??

from mongoose.

FaizBShah avatar FaizBShah commented on June 24, 2024

Other than the error, what are the logs its printing? Like, is it printing any of the above logs mentioned in the code? Also, is it working by just doing await mongoose.connect()?

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024

it does console log that its connected, and it always worked, what else should I do. and this is the only error I am getting

from mongoose.

FaizBShah avatar FaizBShah commented on June 24, 2024

It looks like the issue is with the code where you are using the findOne() option. Can you share that code? If possible, try to share a reproducible code

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024
const mongoose = require('mongoose');
const mongoUrl = require('../config.js').mongourl;
const { ChalkAdvanced } = require('chalk-advanced');
const schedule = require('node-schedule');

const dataSchema = new mongoose.Schema({
  key: String,
  value: mongoose.Schema.Types.Mixed
});

const Data = mongoose.model('AutoDelete', dataSchema);

class Database {
  constructor() {
    this.db = mongoose.connection;
    this.db.on('error', console.error.bind(console, 'MongoDB connection error:'));
    this.scheduleCleanup('messagesDeleted', '0 0 * * 0'); // Once a week (Sunday)
    this.scheduleCleanup('messagesDeletedMonth', '0 0 1 * *'); // First day of every month
    this.scheduleCleanup('messagesDeletedYear', '0 0 1 1 *'); // First day of every year
  }
  
  
  async connect() {
    if (mongoose.connection.readyState === 0) {
      try {
        console.log(`${ChalkAdvanced.blue('Database: ')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.yellow('connecting...')}`);
        await mongoose.connect(`${mongoUrl}`, { serverSelectionTimeoutMS: 5000 }); // Increased timeout
        if (mongoose.connection.readyState === 1){
        console.log(`${ChalkAdvanced.blue('Database: ')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.green('Successfully connected')}`);
      } else {
        console.log(`STATE OF THE DB HEREEEEEEEEEEEE : ${mongoose.connection.readyState}`)
      } 
      } catch (err) {
        console.error(err);
        throw err;
      }
    } else {
      console.log('Already connected to database.');
    }
  }

  async disconnect() {
    if (mongoose.connection.readyState !== 0) {
      try {
        await mongoose.disconnect();
        console.log(`${ChalkAdvanced.blue('Database: ')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.red('has been disconnected')}`);
      } catch (err) {
        console.error(err);
      }
    } else {
      console.log('Already disconnected from database.');
    }
  }

  async set(key, value) {
    const existingData = await Data.findOne({ key: key }).exec();
  
    if (existingData) {
      existingData.value = { ...existingData.value, ...value };
      await existingData.save();
    } else {
      const newData = new Data({
        key: key,
        value: value
      });
      await newData.save();
    }
  }

  async autodelete(key, value, forceSetToZero = false) {
    const existingData = await Data.findOne({ key: key }).exec();

    if (existingData) {
      if (forceSetToZero) {
        // If forceSetToZero is true, set the value to zero regardless of the existing value
        existingData.value = 0;
      } else if (typeof existingData.value === 'number') {
        // If the existing value is a number, add the new value to it
        existingData.value += value;
      } else {
        // If the existing value is not a number, set it to the new value
        existingData.value = value;
      }

      await existingData.save();
    } else {
      // If the key doesn't exist, create a new document with the specified value
      const newData = new Data({
        key: key,
        value: value
      });

      await newData.save();
    }
  }


  async get(key) {
    const data = await Data.findOne({ key: key }).exec();
    if (data) {
      return data.value;
    } else {
      return undefined;
    }
  }

  async add(key, value) {
    const data = await Data.findOne({ key: key }).exec();
    if (data) {
      data.value += value;
      await data.save();
    } else {
      const newData = new Data({
        key: key,
        value: value
      });
      await newData.save();
    }
  }

  async delete(key) {
    await Data.findOneAndDelete({ key: key }).exec();
  }

  async push(key, values) {
    const data = await Data.findOne({ key: key }).exec();
  
    if (data) {
      // Ensure that 'value' is an object
      if (typeof data.value === 'object') {
        // Check if the specified properties exist in the object
        for (const property in values) {
          if (values.hasOwnProperty(property)) {
            if (!data.value.hasOwnProperty(property)) {
              // If the property doesn't exist, create it as an array
              data.value[property] = [];
            }
  
            // Use $addToSet to add unique values to the array
            await Data.updateOne({ key: key }, { $addToSet: { [`value.${property}`]: values[property] } });
          }
        }
      } else {
        // If 'value' is not an object, create a new object with the specified values
        const newData = new Data({
          key: key,
          value: values
        });
        await newData.save();
      }
    } else {
      // If the key doesn't exist, create a new document with the specified values
      const newData = new Data({
        key: key,
        value: values
      });
      await newData.save();
    }
  }
  
  
  
  
  
  

  async pull(key, value) {
    await Data.updateOne({ key: key }, { $pull: { value: value } });
  }

 
  async remove(key, values) {
    const data = await Data.findOne({ key: key }).exec();
  
    if (data && typeof data.value === 'object') {
      // Ensure that 'value' is an object
      if (typeof data.value === 'object') {
        // Check if the specified properties exist in the object
        for (const property in values) {
          if (values.hasOwnProperty(property)) {
            // Use $pull to remove the specified values from the array
            await Data.updateOne({ key: key }, { $pull: { [`value.${property}`]: values[property] } });
          }
        }
      }
  
      // Save the updated document
      await data.save();
    }
    // If the key doesn't exist or the property doesn't exist, no action is taken
  }
  
  

  async has(key) {
    const data = await Data.findOne({ key: key }).exec();
    if (data) {
      return true;
    } else {
      return false;
    }
  }

  async hasIn(key, value) {
    const hasIn = await this.get(key);
    if (hasIn && hasIn.includes(value)) {
      return true;
    } else {
      return false;
    }
  }
  

  async scheduleCleanup(collectionName, cronExpression) {
    schedule.scheduleJob(cronExpression, async () => {
      await this.delete(collectionName);
      console.log(`${ChalkAdvanced.blue('Database Cleanup:')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.green(`${collectionName} deleted`)}`);
    });
  }
}

module.exports = Database;

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024
const mongoose = require('mongoose');
const mongoUrl = require('../config.js').mongourl;
const { ChalkAdvanced } = require('chalk-advanced');
const schedule = require('node-schedule');

const dataSchema = new mongoose.Schema({
  key: String,
  value: mongoose.Schema.Types.Mixed
});

const Data = mongoose.model('AutoDelete', dataSchema);

class Database {
  constructor() {
    this.db = mongoose.connection;
    this.db.on('error', console.error.bind(console, 'MongoDB connection error:'));
    this.scheduleCleanup('messagesDeleted', '0 0 * * 0'); // Once a week (Sunday)
    this.scheduleCleanup('messagesDeletedMonth', '0 0 1 * *'); // First day of every month
    this.scheduleCleanup('messagesDeletedYear', '0 0 1 1 *'); // First day of every year
  }
  
  
  async connect() {
    if (mongoose.connection.readyState === 0) {
      try {
        console.log(`${ChalkAdvanced.blue('Database: ')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.yellow('connecting...')}`);
        await mongoose.connect(`${mongoUrl}`, { serverSelectionTimeoutMS: 5000 }); // Increased timeout
        if (mongoose.connection.readyState === 1){
        console.log(`${ChalkAdvanced.blue('Database: ')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.green('Successfully connected')}`);
      } else {
        console.log(`STATE OF THE DB HEREEEEEEEEEEEE : ${mongoose.connection.readyState}`)
      } 
      } catch (err) {
        console.error(err);
        throw err;
      }
    } else {
      console.log('Already connected to database.');
    }
  }

  async disconnect() {
    if (mongoose.connection.readyState !== 0) {
      try {
        await mongoose.disconnect();
        console.log(`${ChalkAdvanced.blue('Database: ')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.red('has been disconnected')}`);
      } catch (err) {
        console.error(err);
      }
    } else {
      console.log('Already disconnected from database.');
    }
  }

  async set(key, value) {
    const existingData = await Data.findOne({ key: key }).exec();
  
    if (existingData) {
      existingData.value = { ...existingData.value, ...value };
      await existingData.save();
    } else {
      const newData = new Data({
        key: key,
        value: value
      });
      await newData.save();
    }
  }

  async autodelete(key, value, forceSetToZero = false) {
    const existingData = await Data.findOne({ key: key }).exec();

    if (existingData) {
      if (forceSetToZero) {
        // If forceSetToZero is true, set the value to zero regardless of the existing value
        existingData.value = 0;
      } else if (typeof existingData.value === 'number') {
        // If the existing value is a number, add the new value to it
        existingData.value += value;
      } else {
        // If the existing value is not a number, set it to the new value
        existingData.value = value;
      }

      await existingData.save();
    } else {
      // If the key doesn't exist, create a new document with the specified value
      const newData = new Data({
        key: key,
        value: value
      });

      await newData.save();
    }
  }


  async get(key) {
    const data = await Data.findOne({ key: key }).exec();
    if (data) {
      return data.value;
    } else {
      return undefined;
    }
  }

  async add(key, value) {
    const data = await Data.findOne({ key: key }).exec();
    if (data) {
      data.value += value;
      await data.save();
    } else {
      const newData = new Data({
        key: key,
        value: value
      });
      await newData.save();
    }
  }

  async delete(key) {
    await Data.findOneAndDelete({ key: key }).exec();
  }

  async push(key, values) {
    const data = await Data.findOne({ key: key }).exec();
  
    if (data) {
      // Ensure that 'value' is an object
      if (typeof data.value === 'object') {
        // Check if the specified properties exist in the object
        for (const property in values) {
          if (values.hasOwnProperty(property)) {
            if (!data.value.hasOwnProperty(property)) {
              // If the property doesn't exist, create it as an array
              data.value[property] = [];
            }
  
            // Use $addToSet to add unique values to the array
            await Data.updateOne({ key: key }, { $addToSet: { [`value.${property}`]: values[property] } });
          }
        }
      } else {
        // If 'value' is not an object, create a new object with the specified values
        const newData = new Data({
          key: key,
          value: values
        });
        await newData.save();
      }
    } else {
      // If the key doesn't exist, create a new document with the specified values
      const newData = new Data({
        key: key,
        value: values
      });
      await newData.save();
    }
  }
  
  
  
  
  
  

  async pull(key, value) {
    await Data.updateOne({ key: key }, { $pull: { value: value } });
  }

 
  async remove(key, values) {
    const data = await Data.findOne({ key: key }).exec();
  
    if (data && typeof data.value === 'object') {
      // Ensure that 'value' is an object
      if (typeof data.value === 'object') {
        // Check if the specified properties exist in the object
        for (const property in values) {
          if (values.hasOwnProperty(property)) {
            // Use $pull to remove the specified values from the array
            await Data.updateOne({ key: key }, { $pull: { [`value.${property}`]: values[property] } });
          }
        }
      }
  
      // Save the updated document
      await data.save();
    }
    // If the key doesn't exist or the property doesn't exist, no action is taken
  }
  
  

  async has(key) {
    const data = await Data.findOne({ key: key }).exec();
    if (data) {
      return true;
    } else {
      return false;
    }
  }

  async hasIn(key, value) {
    const hasIn = await this.get(key);
    if (hasIn && hasIn.includes(value)) {
      return true;
    } else {
      return false;
    }
  }
  

  async scheduleCleanup(collectionName, cronExpression) {
    schedule.scheduleJob(cronExpression, async () => {
      await this.delete(collectionName);
      console.log(`${ChalkAdvanced.blue('Database Cleanup:')} ${ChalkAdvanced.gray('>')} ${ChalkAdvanced.green(`${collectionName} deleted`)}`);
    });
  }
}

module.exports = Database;

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024

That is it , and I use the connect here :

const { ShardingManager } = require('discord.js');
const fs = require('fs');
const config = require('./src/config.js');
const { ChalkAdvanced } = require('chalk-advanced');
const manager = new ShardingManager('./main.js', { token: config.token, respawn: true });
const on = require("./website/server.js");
const { Auto } = require('./src/structures/bot.js');
const abot = new Auto();
const Database = require("./src/utils/Database.js");
const db = new Database();
db.connect();
on(abot);
//...

from mongoose.

donoftime2018 avatar donoftime2018 commented on June 24, 2024

Why not use then() or await/async for where the mongoose connection statement?

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024

Does the connection appear on the dashboard of mongoose??

yes !? (if u mean the metrics on mongodb cloud)

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024

After some testing, indeed findOne gets timed out. but I dont know why tho. findOne is still a function, and I assume that the code is correctly written (which obviously is not since I have this bugs)

from mongoose.

FaizBShah avatar FaizBShah commented on June 24, 2024

@Sigmaxii Maybe this stack overflow answer might help you - https://stackoverflow.com/questions/65408618/mongooseerror-operation-users-findone-buffering-timed-out-after-10000ms.

Also, before that, can you allow access from everywhere (0.0.0.0) instead of just your IP address to check whether its not an issue due to your IP or VPS

from mongoose.

donoftime2018 avatar donoftime2018 commented on June 24, 2024

Are you connecting using 127.0.0.1 or localhost?

from mongoose.

vkarpov15 avatar vkarpov15 commented on June 24, 2024

Is there any indication that your code called disconnect()?

Also, can you please paste the output of npm list mongoose?

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024

Is there any indication that your code called disconnect()?

Also, can you please paste the output of npm list mongoose?

Currently no, disconnect is not called anywhere, and as mentioned in the description, mongoose version is 8.2

from mongoose.

Sigmaxii avatar Sigmaxii commented on June 24, 2024

@Sigmaxii Maybe this stack overflow answer might help you - https://stackoverflow.com/questions/65408618/mongooseerror-operation-users-findone-buffering-timed-out-after-10000ms.

Also, before that, can you allow access from everywhere (0.0.0.0) instead of just your IP address to check whether its not an issue due to your IP or VPS

  • About the stack overflow:
  • This is not helping since its all about mongoose 5.x
  • About the IP access:
  • Yes I do allow access from everywhere thats not the issue

from mongoose.

vkarpov15 avatar vkarpov15 commented on June 24, 2024

"mentioned in the description, mongoose version is 8.2" <-- I understand, I'm asking for the output of npm list mongoose to rule out multiple versions of Mongoose.

Also, are you connecting to localhost or a remote server?

from mongoose.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.