Connect to MongoDB atlas cluster with flask-mongoengine - mongodb

I am trying to connect with mongodb atlas from my flask app using flask-mongoengine.
DB_URI = "mongodb+srv://flask_app_user:flask_app_user#cluster0.6jwadcx5g.mongodb.net/flask_app?retryWrites=true&w=majority"
def create_app():
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'replace_me_32437264278642')
app.config['MONGODB_SETTINGS'] = {
'host': os.environ.get('MONGODB_URI', DB_URI)
}
MongoEngine(app)
socketio.init_app(app)
SSLify(app)
return app
But I am getting an error,
pymongo.errors.InvalidURI: Invalid URI scheme: URI must begin with 'mongodb://'
How can I use mongo atlas with flask_mongoengine?
I don't want to stick with flask_mongoengine. I don't want to change that.

It worked correctly for me with the latest version flask_mongoengine-1.0.0 and pymongo-3.11.2
It seems you're using the host from MONGODB_URI env var...
What do you have in MONGODB_URI??
Could you share also which version are you using?

Related

NextJs + Mongoose + Mongo Atlas multiple connections even with caching

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?

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?

Intermittent TimeoutException connecting Atlas MongoDb from .net core 2.2 at Linux-based docker container on Azure

I have an application based using .Net Core 2.2 that is connecting to MondoDb cluster V3.6 in Atlas. The application is hosted in Azure as a Linux Docker container. The app is using MongoDB .Net driver 2.7.3. The app periodically (once in a couple minutes) receives the following timeout exceptions:
System.TimeoutException at MongoDB.Driver.Core.Clusters.Cluster.ThrowTimeoutException
and
System.TimeoutException at MongoDB.Driver.Core.Connections.TcpStreamFactory.ConnectAsync
The mongo client instance is configured according to the MongoDb docs, i.e.
var url = MongoUrl.Create("mongodb+srv://user:password#cluster.gcp.mongodb.net/?authSource=admin&retryWrites=true&ssl=true");
var clientSettings = MongoClientSettings.FromUrl(url);
clientSettings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12 };
void SocketConfigurator(Socket s) => s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
clientSettings.ClusterConfigurator = builder =>
builder.ConfigureTcp(tcp => tcp.With(socketConfigurator: (Action<Socket>)SocketConfigurator));
return new MongoClient(clientSettings);
I checked number of SO questions including MongoDB C# 2.0 TimeoutException and SocketTimeout with opened connection in MongoDB but the suggestions seem to be either outdated (reported as fixed in the current version of driver) or don't have permanent positive effect (setting timeouts in the connection string i.e. connectTimeoutMS=90000&socketTimeoutMS=90000&maxIdleTimeMS=90000). The second one (setting tcp_keepalive_time) seems to be not applicable to a docker container in Azure. Please help.
Have you tried setting like this:
var client = new MongoClient(new MongoClientSettings
{
Server = new MongoServerAddress("xxxx"),
ClusterConfigurator = builder =>
{
builder.ConfigureCluster(settings => settings.With(serverSelectionTimeout: TimeSpan.FromSeconds(10)));
}
});

How to change Pymongo database connection

I do have a database named users but pymongo is looking for a db named as app is there any way to change to Pymongo connection method ?
this one is working if i crate a db named as app;
app = Flask(__name__)
mongo = PyMongo(app)
i want to connect like this but i do get an error for that ;
mongo = PyMongo('users')
I have found my answer;
client = MongoClient('localhost')
db = client['dbname']
collection = db.collection_name
app = Flask(__name__)
app.config['MONGO_DBNAME'] = 'dbname'
mongo = PyMongo(app)
This allows you to use flask_pymongo, more info here

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