How do I connect TypeORM to MongoDB? I receive errors while trying to connect - mongodb

I have a NestJS and TypeORM project going. I am trying to connect it to my MongoDB database.
Here is the list of my MongoDB projects from the https://cloud.mongodb.com/ website:
The only name I can see for these is "cluster0" like here:
And then in my .env file I have:
MONGODB_CONNECTION_STRING=mongodb+srv://roland:<myActualPassword>#cluster0.7llne.mongodb.net/?retryWrites=true&w=majority
MONGODB_DATABASE=cluster0
and then the entrypoint to the application:
import { Module } from "#nestjs/common";
import { SchedulingController } from "./scheduling.controller";
import { SchedulingService } from "./scheduling.service";
import { ConfigModule } from "#nestjs/config";
import { TypeOrmModule } from "#nestjs/typeorm";
import { Meeting } from "./db/Meeting.entity";
#Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: "mongodb",
url: process.env.MONGODB_CONNECTION_STRING,
database: process.env.MONGODB_DATABASE,
entities: [__dirname + "/**/*.entity{.ts,.js}"],
ssl: true,
useUnifiedTopology: true,
useNewUrlParser: true,
}),
TypeOrmModule.forFeature([Meeting]),
],
controllers: [SchedulingController],
providers: [SchedulingService],
})
export class SchedulingModule {}
But I see these errors:
[Nest] 16760 - 2022-05-16, 10:05:09 p.m. ERROR [TypeOrmModule] Unable to connect to the database. Retrying (5)...
MongoServerSelectionError: read ECONNRESET
at Timeout._onTimeout (C:\Users\jenfr\Documents\Code2022\TakeHomeTests\bluescape\bluescape\node_modules\mongodb\src\sdam\topology.ts:594:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
[Nest] 16760 - 2022-05-16, 10:05:42 p.m. ERROR [TypeOrmModule] Unable to connect to the database. Retrying (6)...
MongoServerSelectionError: read ECONNRESET
at Timeout._onTimeout (C:\Users\jenfr\Documents\Code2022\TakeHomeTests\bluescape\bluescape\node_modules\mongodb\src\sdam\topology.ts:594:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
[Nest] 16760 - 2022-05-16, 10:06:15 p.m. ERROR [TypeOrmModule] Unable to connect to the database. Retrying (7)...
MongoServerSelectionError: read ECONNRESET
at Timeout._onTimeout (C:\Users\jenfr\Documents\Code2022\TakeHomeTests\bluescape\bluescape\node_modules\mongodb\src\sdam\topology.ts:594:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
edit: I'm fairly certain my MONGODB_CONNECTION_STRING and MONGODB_DATABASE are set properly, anyone know what else could be causing these errors?

Try to set useUnifiedTopology=false.

Related

error uploading API REST + BD (express - sequelize - postgress) in railway

I use express and sequelize ORM to connect to a Postgres database on my laptop.
In the deploy logs figures this. I was using Heroku, I'm new to railway
ConnectionError [SequelizeConnectionError]: connect ETIMEDOUT 35.197.113.116:5432
at Client._connectionCallback (/app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:143:24)
at Client._handleErrorWhileConnecting (/app/node_modules/pg/lib/client.js:305:19)
at Client._handleErrorEvent (/app/node_modules/pg/lib/client.js:315:19)
at Connection.emit (node:events:513:28)
at Socket.reportStreamError (/app/node_modules/pg/lib/connection.js:52:12)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
parent: Error: connect ETIMEDOUT 35.197.113.116:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -110,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.197.113.116',
port: 5432
},
original: Error: connect ETIMEDOUT 35.197.113.116:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1247:16) {
errno: -110,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '35.197.113.116',
port: 5432
}
}

GitLab pipeline - postgres connection termined unexpectedly

I am having a little trouble with postgres in docker .. I am running this pipeline in gitlab ... and everything starts fine.. I start a postgres:14-alpine docker image and run unit tests of the application ... and when it's about to start (create the test database) ...
I tried increasing the timeouts
pool: {
max: 50,
min: 5,
idle: 600000, // 10min
acquire: 600000,
createTimeoutMillis: 600000,
acquireTimeoutMillis: 600000,
idleTimeoutMillis: 600000,
reapIntervalMillis: 600000,
createRetryIntervalMillis: 600000
}
but it keeps ending up with this "Connection terminated unexpectedly"
Creating database db_unittests, owner will be postgres.
Executing (default): CREATE DATABASE db_unittests WITH OWNER = postgres;
/builds/project/node_modules/sequelize/lib/dialects/postgres/query.js:386
return new sequelizeErrors.DatabaseError(err);
^
DatabaseError [SequelizeDatabaseError]: Connection terminated unexpectedly
at Query.formatError (/builds/project/node_modules/sequelize/lib/dialects/postgres/query.js:386:16)
at Query.run (/builds/project/node_modules/sequelize/lib/dialects/postgres/query.js:87:18)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async /builds/project/node_modules/sequelize/lib/sequelize.js:619:16
at async run (/builds/project/tests/scripts/database-recreate.js:50:3) {
parent: Error: Connection terminated unexpectedly
at Connection.<anonymous> (/builds/project/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:627:28)
at Connection.emit (node:events:513:28)
at Socket.<anonymous> (/builds/project/node_modules/pg/lib/connection.js:107:12)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
sql: 'CREATE DATABASE db_unittests WITH OWNER = postgres;',
parameters: undefined
},
original: Error: Connection terminated unexpectedly
at Connection.<anonymous> (/builds/project/node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:627:28)
at Connection.emit (node:events:513:28)
at Socket.<anonymous> (/builds/project/node_modules/pg/lib/connection.js:107:12)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1358:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
sql: 'CREATE DATABASE db_unittests WITH OWNER = postgres;',
parameters: undefined
},
sql: 'CREATE DATABASE db_unittests WITH OWNER = postgres;',
parameters: undefined
}
Locally, it all works fine .. only in the pipeline - it acting up :disappointed:
Any idea why is that so? Thanks a lot

NestJS TypeORM syntax error in migration file

I was going through the NestJS official docs. I set up PostgreSQL on Heroku, connected with TypeORM, run a migration and after that my app started crushing. I tried different approaches and searched blogs/issues on github/questions here, but nothing helped.
Here is an error:
[Nest] 46723 - 05/10/2020, 6:33:42 PM [InstanceLoader] TypeOrmModule dependencies initialized +84ms
[Nest] 46723 - 05/10/2020, 6:33:43 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)... +493ms
/Users/Shared/diploma/be/migration/1589119433066-AddUser.ts:1
import {MigrationInterface, QueryRunner} from "typeorm";
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Function.PlatformTools.load (/***/PROJECT_ROOT/node_modules/typeorm/platform/PlatformTools.js:114:28)
at /***/PROJECT_ROOT/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69
at Array.map (<anonymous>)
Here is my ormconfig.json:
"type": "postgres",
"url": "postgres://***",
"ssl": true,
"extra": {
"ssl": {
"rejectUnauthorized": false
}
},
"entities": ["dist/**/*.entity{.ts,.js}"],
"migrationsTableName": "custom_migration_table",
"migrations": ["migration/*{.ts,.js}"],
"cli": {
"migrationsDir": "migration"
}
}
migration was generated using ts-node ./node_modules/.bin/typeorm migration:generate -n AddUser
I'm using nest start --watch command to start the app.
Migration file {TIMESTAMP}-AddUser.ts:
import {MigrationInterface, QueryRunner} from "typeorm";
export class AddUser1589119433066 implements MigrationInterface {
name = 'AddUser1589119433066'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "users" (...)`, undefined);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "users"`, undefined);
}
}
Thanks to #Isolated!
I've changed the ormconfig.json so entities and migrations files looks like this now and it works fine for me:
"entities": ["dist/**/*.entity{.ts,.js}"],
"migrations": ["dist/migration/*{.ts,.js}"],

Error: connection timeout - expressjs mongodb mongoose

I'm new to express/node and web programming in general. What is the best way to deal with this error when mongoose's mongodb connection times out, this is how I connect:
mongoose.connect(config.mongoUrl);
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'error connecting with mongodb database:'));
db.once('open', function() {
console.log('connected to mongodb database');
});
This is the error when it times out while my server is running:
error connecting with mongodb database: Error: connection timeout
at Db. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongoose\lib\drivers\node-mongodb-native\connection.js:169:17)
at emitTwo (events.js:106:13)
at Db.emit (events.js:191:7)
at Server.listener (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb\lib\db.js:1798:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Server. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb\lib\server.js:274:14)
at emitOne (events.js:96:13)
at Server.emit (events.js:188:7)
at Pool. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb-core\lib\topologies\server.js:335:12)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection. (C:\Users\Sean\OneDrive\webpages\000\lasttry\node_modules\mongodb-core\lib\connection\pool.js:270:12)
at Connection.g (events.js:291:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
How about on disconnect just reconnect to mongo. See below:
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'error connecting with mongodb database:'));
db.once('open', function() {
console.log('connected to mongodb database');
});
db.on('disconnected', function () {
//Reconnect on timeout
mongoose.connect(config.mongoUrl);
db = mongoose.connection;
});
You can also set a timeout value on the connection.
mongoose.connect(url, { server: { socketOptions: { connectTimeoutMS: 1000 }}}, function(err) { ... });
Also, make sure that mongo is still running on your machine. A connection timeout could mean mongo isn't running.
Reference: Another stack overflow question
Check mongod is running.
typing mongo in shell.
Add connectTimeoutMS=300000 paramter for you uri.
uri looks like mongodb://localhost/collectionName?connectTimeoutMS=300000

protractor sets error without opening browser

i download a new ionic project and i am trying to test the header contains these elements ""
my config file is
exports.config = {
framework: 'jasmine2',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['../www/head.spec.js'],
multiCapabilities: [
{
browserName: 'chrome'
}]
}
named this as e2e.js
my test case file is
describe('header Module', function(){
var header;
beforeEach(function() {
header = element(by.css('title'));
});
it('should check title text',function(){
expect(header.getText()).toContain('Ionic Blank Starter');
});
});
and i named this as head.spec.js
my issue is that i could see the browser opened and my protractor sends an error msg
empresss-Mac-mini:myApp admin$ protractor test/e2e.js
Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:172
callback(new Error(message));
^
Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:4444
at ClientRequest. (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:172:16)
at emitOne (events.js:77:13)
at ClientRequest.emit (events.js:169:7)
at Socket.socketErrorListener (_http_client.js:259:9)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1253:8)
at doNTCallback2 (node.js:439:9)
at process.tickCallback (node.js:353:17)
From: Task: WebDriver.createSession()
at Function.webdriver.WebDriver.acquireSession (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:157:22)
at Function.webdriver.WebDriver.createSession (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:131:30)
at [object Object].Builder.build (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/builder.js:445:22)
at [object Object].DriverProvider.getNewDriver (/usr/local/lib/node_modules/protractor/lib/driverProviders/driverProvider.js:38:7)
at [object Object].Runner.createBrowser (/usr/local/lib/node_modules/protractor/lib/runner.js:182:37)
at /usr/local/lib/node_modules/protractor/lib/runner.js:263:21
at _fulfilled (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:797:54)
at self.promiseDispatch.done (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:826:30)
at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:759:13)
at /usr/local/lib/node_modules/protractor/node_modules/q/q.js:525:49
[launcher] Process exited with error code 1
could someone help to fix this issue
when i try to webdriver-manager update err msg is displayed
empresss-Mac-mini:~ admin$ webdriver-manager update
fs.js:799
return binding.mkdir(pathModule._makeLong(path),
^
Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/protractor/selenium'
at Error (native)
at Object.fs.mkdirSync (fs.js:799:18)
at Object.<anonymous> (/usr/local/lib/node_modules/protractor/bin/webdriver-manager:126:6)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
at node.js:961:3
empresss-Mac-mini:~ admin$