NextJs + Mongoose + Mongo Atlas multiple connections even with caching - mongodb

I am using NextJS to build an app. I am using MongoDB via mongoosejs to connect to my database hosted in mongoAtlas.
My database connection file looks like below
import mongoose from "mongoose";
const MONGO_URI =
process.env.NODE_ENV === "development"
? process.env.MONGO_URI_DEVELOPMENT
: process.env.MONGO_URI_PRODUCTION;
console.log(`Connecting to ${MONGO_URI}`);
const database_connection = async () => {
if (global.connection?.isConnected) {
console.log("reusing database connection")
return;
}
const database = await mongoose.connect(MONGO_URI, {
authSource: "admin",
useNewUrlParser: true
});
global.connection = { isConnected: database.connections[0].readyState }
console.log("new database connection created")
};
export default database_connection;
I have seen this MongoDB developer community thread and this GitHub thread.
The problem seems to happen only in dev mode(when you run yarn run dev). In the production version hosted on Vercel there seems to be no issue. I understand that in dev mode the server is restarted every time a change is saved so to cache a connection you need to use as global variable. As you can see above, I have done exactly that. The server even logs: reusing database connection, then in mongoAtlas it shows like 10 more connections opened.
How can I solve this issue or what am I doing wrong?

Related

I could not connect Strapi with MongoDB using Visual Studio Code. Please assist me in this

And I am repeatedly getting the following error message:
Where is the problem? How do I connect strapi to MongoDD?
You need to first connect to MongoDB locally. Keep everything blank, or enter the values for your locally running instance of MongoDB. Then, you can retrieve the connection URL from Atlas or wherever, and then you need to edit your config/database.js:
module.exports = ({ env }) => ({
defaultConnection: 'default',
connections: {
default: {
connector: 'mongoose',
settings: {
uri: env('DATABASE_URI')
},
options: {
ssl: true
}
}
}
});
Then, in your .env file:
DATABASE_URI=[CONNECTION_STRING_HERE]
Restart the server and you will be connected with your cloud instance of MongoDB.
If you still have issues, you can see the strapi docs: https://strapi.io/documentation/developer-docs/latest/guides/databases.html#install-on-atlas-mongodb-atlas.

Unable to create connection to MongoDB server in `mongod` shell

My MongoDB was working fine but at some point, I was facing issues to connect my express server with the DB. when I start the DB using mongod it shows me 2020-05-21T14:36:41.819+0600 I NETWORK [initandlisten] waiting for connections on port 27017 which seems like a normal "running" entry. Then I run my express server where I connect the DB like this:
...
const mongoose = require('mongoose');
const url = 'mongodb://localhost:27017/db_name';
const connect = mongoose.connect(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
connect.then(
(db) => {
console.log('Connected correctly to server');
},
(err) => {
console.log(err);
}
);
...
which log Connected correctly to server but when I see the mongod running shell then there still the message which showed that it still waiting for the connection. And the most surprising issue is I can perform database related work in my express server. when I check the document using mongo, I see they correctly added to the database. I can't understand then why mongod behave like this. here is the full log of the mongod shell.
Update:
I forgot to add one important piece of information which is whenever I start my MongoDB server using mongod, in the C:\data\db directory there generate a new mongod.lock file. I tried to delete it and restart my server but eventually it generates again.

Connect to MongoDB in Quasar / VueJS

I am trying to setup mongoDB in my Project (using Quasar Framework)
What I did for preparation:
Setup MongoDB Atlas on Windows and create a user, a database and a collection
Create a Connection String
installed mongodb in node_modules (npm install —-save mongodb)
What I tested
Using axios to get test data in JSON format (worked)
Using axios to access the mongoDB (Didn't find a way to do it - Maybe this is not supported)
creating a separate js file to connect to mongoDB (see below)
Access mongoDB via js
After I failed to access mongoDB with axios I tried to connect using this code:
const mongo = require('mongodb')
const MongoClient = mongo.MongoClient
const uri = YOUR_CONNECTION_STRING
var client;var mongoClient = new MongoClient(uri, { reconnectTries :
Number.MAX_VALUE, autoReconnect : true, useNewUrlParser : true })
mongoClient.connect((err, db) => { // returns db connection
if (err != null) {
console.log(err)
return
}
client = db
})
Problem here is, I don't know how to implement this into my vue/quasar app. Do I have to save this as a component or can I access it directly using <script src="app.js">?
Is using the above code the correct way to connect to my mongoDB database or is there an easier way?

Can not connect Azure Functions to MongoDB (created in azure)

I have a MongoDB setup on azure, and I am tring to connect to it via azure function.
These are the steps I took:
Creating a Simple Azure Function
Installed the MongoDB Driver on Azure, To install the MongoDB Node.js driver, I went go to .scm.azurewebsites.net, and clicked on 'Debug Console' -> 'PowerShell'.
I Navigated to the D:\home\site\wwwroot directory and clicked on the plus icon to create a new file called package.json.
I Created and saved the below package.json file.
{
"name": "nameofunction",
"dependencies": {
"mongodb": "3.x"
}
}
Next, I ran npm install from the shell.
From the Azure Function I should be able to connect to MongoDB and execute a query using the below code.
const mongodb = require('mongodb');
const url = "mongodb://cosmod: <PASSWORD>==#cosmodb.documents.azure.com:10255/?ssl=true&replicaSet=globaldb";
module.exports = async function (context, req) {
mongodb.connect(url, function(error, client) {
if (error) throw error;
var dbo = client.db("mydb");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
context.log("Collection created!");
db.close();
});
});
};
My code is throwing up a Status: 500 Internal Server Error
The more I look at the code, the more i can not understand why this should not work.
The package-lock.jsonhas all the dependencies loaded after I ran npm install in the shell.
I appreciate any help in resolving this.
This seems weired, I also followed same and was able to connect to my db.
Can you please check your cosmos connectiondb, mongo compatible connection string? Are you able to connect that from other mongo clients
Status: 500 Internal Server Error
I assume that it dues to the code mongodb.connect(url, function(error, client)
please change the code to
mongodb.MongoClient.connect(uri, function(error, client)
A review of the Azure Cosmos DB account- Quick start documentation accessible via the Azure Cosmos DB account menu side blade; connecting the MongoDB app is among others via:
the Node.js 2.2 driver and
the Node.js 3.0 driver
I was using the Node.js 2.2 driver connection string in the azure function which is not compatible with the Node.js 3+ driver dependency in my app. Using the Node.js 3.0 driver connection string, I was able to connect the MongoDB app, without the error. The double equality sign in the password string is url encoded in the 3+ driver.
Node.js 3+ driver connection string
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://cosmodb:<PWD>%3D%3D#cosmodb.documents.azure.com:10255/?ssl=true", function (err, client) {
client.close();
});
Node.js 2.2 driver connection string
var mongoClient = require("mongodb").MongoClient;
mongoClient.connect("mongodb://cosmodb:<PWD>==#cosmodb.documents.azure.com:10255/?ssl=true", function (err, db) {
db.close();
});

nodejs chat example does not work

I've come across a node chat example on github, When I try to run it, I see the following error:
Error connecting to mongo perhaps it isn't running ?
I've installed mongo 0.9.2, nodejs 5.2 pre, npm 3.0 and other dependencies. The example can be found here: https://github.com/gregstewart/chat.io
I can not determine whether if the example not really works or I didn't run it right. Please help.
Did you install and start mongo-db on your system? This error is mostly because of a missing mongo instance running on the local machine.
Check out the follwing code excerpts from chat.io.
main.js:
/**
* Configure the user provider (mongodB connection for user data storage)
*/
var userProvider = new UserProvider('localhost', 27017);
Creates a new UserProvider object using host and port for database (localhost:27017, mongo-db default).
UserProvider.js:
UserProvider = function(host, port) {
this.db = new mongo.Db('node-mongo-chat', new Server(host, port, {auto_reconnect: true}, {}));
this.db.addListener('error', function(error) {
console.log('Error connecting to mongo -- perhaps it isn\'t running?');
});
this.db.open(function() {
});
};
Opening the connection to the server, printing out an error on failure (the error you mentioned above).
Consider reading up on the mongo-db docs concerning installation and setup here