NestJS: Unable to connect to MongoDB using MongooseModule.forRootAsync - nestjs

I am trying to connect to local mongoDB in the AppModule by doing the following but it won't connect:
imports: [
MongooseModule.forRootAsync({
useFactory: async () => {
return {
uri: 'mongodb://localhost:27017/client',
useNewUrlParser: true,
useCreateIndex: true,
};
},
}),
],
Error from NestJS:
[MongooseModule] Unable to connect to the database. Retrying (1)...
The MongoDB is running fine. I can connect to it through MongoDB Compass with the same uri.
What is done wrong causing the connection not being established?

useNewUrlParser , useUnifiedTopology , useFindAndModify , and useCreateIndex are no longer supported options,İf you remove that option everything will works.From the Mongoose 6.0 docs:
MongooseModule.forRootAsync({
useFactory: async () => ({
uri: 'mongodb://localhost:27017/client',
}),
}),

This works with async and logging options
MongooseModule.forRootAsync({
useFactory: async () => {
const connection = await ConnectToMongodb.getConnectionString();
return {
connectionFactory: (connection) => {
if (connection.readyState === 1) {
console.log('Database Connected successfully');
}
connection.on('disconnected', () => {
console.log('Database disconnected');
});
connection.on('error', (error) => {
console.log('Database connection failed! for error: ', error);
});
return connection;
},
uri: connection,
};
},
})

Related

Error: MongooseError: Operation `tours.insertOne()` buffering timed out after 10000ms at Timeout.<anonymous>

I'm running MongoDB Atlas on node express and I got this error.
Also I have set my network access from anywhere.
Every time I use testTours.save() method it somehow invokes the tours.insertOne() method and creates a collection by itself.
What to do?
Here is my code:
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const app = require('./app');
dotenv.config({ path: './config.env' });
const DB = process.env.DATABASE.replace(
'<PASSWORD>',
process.env.DATABASE_PASSWORD
);
async function start() {
try {
await mongoose.connect(DB, () => console.log('DB connection successful'));
} catch (err) {
console.log(err);
}
}
start();
testTour
.save()
.then(doc => {
console.log(doc);
})
.catch(err => {
console.log('Error: ', err);
});
const port = 3000 || process.env.PORT;
app.listen(port, () => {
console.log(`Listening on port ${port}...`);
});
You have to wait for connection to be established
start().then(() => {
testTour
.save()
.then(doc => {
console.log(doc);
})
.catch(err => {
console.log('Error: ', err);
});
})

Operation `users.findOneAndUpdate()` buffering timed out after 10000ms

I am trying to find and update a document from a mongodb database but I am facing this error over and over again
The error
MongooseError: Operation `users.findOneAndUpdate()` buffering timed out after 10000ms
at Timeout.<anonymous> (C:\Development\discord-bot\api\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:148:23)
What I haved tried ?
I have used using async/await for the mongodb connection and still it doesnt work
Code
index.js
client.once('ready', async () => {
console.log('Ready!');
client.user.setActivity(`Mind Meld`, {
type: "PLAYING",
});
await mongo().then(async mongoose => {
try {
console.log('Connected to mongo!!');
}
finally {
mongoose.connection.close();
}
});
});
database/mongo.js
const mongoose = require('mongoose');
require('dotenv').config();
module.exports = async () => {
await mongoose.connect(process.env.MONGODB_URL, {
keepAlive: true,
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(x => {
console.log(
`Connected to Mongo! Database name: "${x.connections[0].name}"`,
);
})
.catch(err => {
console.error('Error connecting to mongo', err);
});
return mongoose;
};
The command
const Discord = require('discord.js')
const User = require('../../../api/database/schemas/user')
const { error, success } = require('../../utils/colors')
module.exports = {
name: 'lobby',
aliases: ['lobby'],
execute(message, args) {
User.findOneAndUpdate({ discordId: message.author.id }, { $set: { playing: true } }, { new: true }, (err, doc) => {
if (err) {
console.log(err)
}
else {
message.reply("done!")
}
})
},
};

Await the database connection

I need to wait the MongoDB database connection.
I have a function that makes a connection and puts a database object into a global variable.
I also have a server startup function in which I want to call the database connection function
async function connectDB() {
const client = new MongoClient(config.DBURL, {useNewUrlParser: true, useUnifiedTopology: true});
await client.connect(err => {
if (err) {
throw err
}
global.dbClient = client
global.db = client.db("db")
console.log("Database Connected!")
});
}
module.exports = {
connectDB: connectDB
}
const connectDB = require('./db').connectDB
app.listen(port, async () => {
await connectDB()
console.log('Server started on: ' + port);
});
I assume your problem is that await client.connect doesn't actually wait. That would indicate that client.connect doesn't actually return a Promise. But you can wrap it in your own:
async function connectDB() {
const client = new MongoClient(config.DBURL, { useNewUrlParser: true, useUnifiedTopology: true });
return new Promise((resolve, reject) => {
client.connect(err => {
if (err) return reject(err);
global.dbClient = client;
global.db = client.db("db");
console.log("Database Connected!");
resolve(client);
});
});
}

Erro to find module when converting ES6 function export to CommonJS

Trying to replicate a push notification project I came cross with this function
import mongoose from 'mongoose';
export default async () => {
// Connect to the database
try {
await mongoose.connect('mongodb://localhost/web-push-notifications', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.set('useCreateIndex', true);
} catch (e) {
console.error(`Couldn't connect to the database: ${e}`);
process.exit(1);
}
};
I convert in this way:
database.js
const mongoose = require('mongoose')
const connection = async () => {
// Connect to the database
try {
await mongoose.connect('mongodb://localhost:27017/web-push-notifications', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.set('useCreateIndex', true);
} catch (e) {
console.error(`Couldn't connect to the database: ${e}`);
process.exit(1);
}
};
module.exports = {connection:connection}
I call that in server.js
const database = require("database")
database.connection();
I receive an error: Cannot find module 'database'
Where Am I missing?

Sequelize authenticate() does not return any result

I am using Sequelize with postgres database.
But authenticate() function does not send any response(whether it is success or failed)
Here is my code.
const connection = new Sequelize('BLIG', 'postgres', 'admin', {
host: 'localhost',
dialect: 'postgres',
define: {
timestamps: false
}
});
app.use('/', (req, res, next) => {
console.clear();
connection.authenticate()
.then(
() => { console.log("Database connected..."), next() },
error=>{console.log("Database connection error",error)}
)
.catch(err => { console.log('database connection error', err), res.redirect('/error') });
})
If anyone knows this issue, help me please.
update your "pg" node package to 8.5.1 or above version using
npm i pg#8.5.1

Resources