Comments (17)
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.
Does the connection appear on the dashboard of mongoose??
from mongoose.
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.
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.
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.
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.
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.
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.
Why not use then() or await/async for where the mongoose connection statement?
from mongoose.
Does the connection appear on the dashboard of mongoose??
yes !? (if u mean the metrics on mongodb cloud)
from mongoose.
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.
@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.
Are you connecting using 127.0.0.1 or localhost?
from mongoose.
Is there any indication that your code called disconnect()
?
Also, can you please paste the output of npm list mongoose
?
from mongoose.
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 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.
"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)
- Improve Documentation HOT 1
- BulkSave on entities with virtual properties *and* a transaction: massive performance hit and OOM crashes HOT 5
- Filter query `Condition` type might as well be `any` HOT 3
- pre middleware .save conflict with strict mode HOT 7
- Date coercion and typechecking inconsistent on `bulkWrite` HOT 3
- Bug while creating document HOT 4
- `validateAllPaths` option to `validate()` and `save()` that validates all paths in the schema, not just modified paths HOT 10
- Nested arrays using `of` result in the incorrect schema type HOT 4
- Why is updateOne invalid if it does not call the then method HOT 2
- Populated documents are flattened to ObjectIds when assigned to another document HOT 5
- Automatically recreate ChangeStream on 'close' event
- Can not update sub schema to empty object HOT 4
- Add a nullable field, its not same as "required" HOT 1
- Turn off "don't cast update pipelines by default" in favor of a more secure approach HOT 2
- Add TypeScript interface for the new PipelineStage - Vector Search HOT 1
- Add `pre` and `post` function types on Query class
- Nested populate with nested paths and subdocuments is not working fine HOT 6
- Best method to set Query and Lean defaults HOT 4
- Issue with 2dsphere indexes in nested schemas vs subdocuments HOT 2
- (Typescript) toObject on populated documents loses the structure
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mongoose.