I'm unable to connect to a mongodb database from a dart application.
I can connect only from terminal and from Compass
I've tried to run a simple example of connecting mongodb database from Dart (see the simple code below):
import 'package:mongo_dart/mongo_dart.dart';
void main() async {
Db db = new Db("mongodb://localhost:27017/test");
await db.open();
print('Connection succeeded!');
//the test database is accessible from Compass or terminal
//localhost:27017 works well
}
await db.open() throws that error:
dart_sdk.js:5822 Uncaught Error: Unsupported operation: Socket
constructor
at Object.dart.throw (dart_sdk.js:4537)
at Function._connect (dart_sdk.js:52279)
at Function.connect (dart_sdk.js:52264)
at mongo_dart._Connection.new.connect (connection.dart:56)
at mongo_dart._ConnectionManager.new._connect
(connection_manager.dart:23)
at _connect.next (<anonymous>)
at runBody (dart_sdk.js:22269)
at Object.async.async (dart_sdk.js:22297)
at mongo_dart._ConnectionManager.new.[_connect]
(connection_manager.dart:22)
at connection_manager.dart:58
at dart_sdk.js:23887
mongo_dart.dart imports dart:io and therefore cannot be used on the web. This package mentions that is is server side.
With the latest build_web_compilers this should be a build time error instead of a runtime error.
You'll need to find, or write, a package for mongoDB that uses dart:html instead of dart:io.
Related
I have an app I am building in flutter and want to connect it to a database in mongo, but can't for the life of me get it to connect, here is a simple dart code to troubleshoot:
it always returns the error:
Unhandled exception:
MongoDB ConnectionException: Could not connect to 127.0.0.1:27017
HandshakeException: Connection terminated during handshake
import 'package:mongo_dart/mongo_dart.dart';
import 'dart:io';
//Platform.environment['MONGO_DART_DRIVER_HOST']
//final mongoURI = Platform.environment['MONGO_DART_DRIVER_HOST'];
final url = "mongodb://127.0.0.1:27017/labelmask";
main() async {
Db _db = new Db(url);
await _db.open(secure: true);
print('connected');
}
Here is what I tried:
-I have tried using dart:io and get Platform.environments, but returned null
-Tried to connect to admin db instead of 'labelmask', same error
-I started first mongod and then mongo
-I can connect to this Database using python(pymongo) and from Compass GUI
-I can run mongo commands in terminal so I know it is connected, just not with dart
I'm currently working on a simple python CRUD script to check MongoDB out. Turns out I'm liking it a lot, but I have found myself being unable to work with MongoDB transactions. Everytime I try to start a transaction an exception is thrown saying:
This MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string.
And, eventhough I've already added that option to my connection string:
self._client = MongoClient('mongodb://localhost/?retryWrites=false')
self._db = self._client.workouts
self._collection = self._db.workouts
That error is still popping up when running the following lines of code:
with self._client.start_session() as s:
with s.start_transaction():
self._collection.delete_one({'_id': id}, session=s)
next = self._collection.find_one({'_id': next_id}, session=s)
return next
What can I do?
I'm running python 3.7.3, pymongo 3.9.0 and MongoDB 4.0.12.
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();
});
I try to connect to a MongoDB Atlas database through mongo_dart with this line of code. The provided link from MongoDB is defined by:
mongodb+srv://<user>:<PASSWORD>#test-asdf.mongodb.net/test?retryWrites=true
throws an "Invalid scheme" Error. When I cut out "+srv" and try to connect with:
Db db = new Db("mongodb://<user>:<password>#test-asdf.mongodb.net/test?retryWrites=true");
it throws a SocketException: Failed host lookup.
Is it even possible to access to a atlas mongoDB or am I forgetting something?
The mongodb+srv:// protocol is for new driver, maybe you can try to click the button "I am using driver 3.4 or earlier" to get the legacy url with mongodb:// protocol
In order to connect to atlas, you need to pass connection string which connect your atlas to mongo_dart like this:
import "package:mongo_dart/mongo_dart.dart;
void getConnection() async {
String connectionString = "mongodb+srv://<user>:<password>#test-asdf.mongodb.net/test?retryWrites=true&w=majority";
print(connectionString);
// Connect to database:
Db db = await Db.create(connectionString);
await db.open();
print(db);
}
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