The database was previously stored on Atlas and now it needs to be transferred to a local server, since there is no access to it due to company restrictions. I’m trying to change the code of the node js application to connect to db but so far without success.
I created a local mongo database and I can connect to it through mongosh.
But I can’t connect node js application to this database.
What i must to change or add into code to connect to local mongodb?
Every time my web application writes - “there is no connection to the database”.
Working for remote DB on Atlas:
connection to db: db → connection → mongodb.ts
import { MongoClient, MongoClientOptions } from "mongodb"
// @TODO should be typed properly, typing HAVE to be improves
const uri = process.env.MONGODB_URI
const dbName = process.env.MONGODB_DB
let cachedClient: any = null
let cachedDb: any = null
export async function connectToDatabase() {
// check the cached.
if (cachedClient && cachedDb) {
// load from cache
return {
client: cachedClient,
db: cachedDb,
}
}
// set the connection options
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
// Connect to cluster
let client = new MongoClient(uri!, opts as MongoClientOptions)
await client.connect()
let db = client.db(dbName)
// set cache
cachedClient = client
cachedDb = db
return {
client: cachedClient,
db: cachedDb,
}
}
is it still writing to Atlas? Maybe your app is caching the connection? Try restarting the NodeJS app and add a console.log(process.env.MONGODB_URI) to verify its getting the right value.
Sorry I’m not indicate that this is previous connection settings mongodb+srv://admin:pass@cluster.xxxxx.mongodb.net/?retryWrites=true&w=majority
And this one is new local connection settings:
1st variant without login and pass mongodb://localhost
2nd variant with credentials mongodb://admin:pass@localhost