-
Notifications
You must be signed in to change notification settings - Fork 35
MongoDb: Establish connection
-
mongo-dart
: MongoDB client for Dart.
open
method on Db
object is used to establish connection to mongo database. close
method on Db
object is used to release the connection at the end of the route handler.
const String mongoUrl = 'mongodb://localhost:27017/myproject'; // MongoDb URL
@Api(path: '/api/todos')
class TodoApi {
@Get(path: '/:id')
Future<Response<String>> getById(Context ctx) async {
String id = ctx.pathParams.id;
final db = new mgo.Db(mongoUrl);
await db.open();
...
await db.close();
...
}
}
-
mongo-dart
: MongoDB client for Dart. -
jaguar_mongo
: mongo interceptor for Jaguar.
jaguar_mongo
package provides MongoPool
interceptor to establish a connection. It automatically releases the connection after at the end of the route chain or when an exception occurs. How well behaved!
MongoPool
interceptor accepts URL to mongo database.
final mgoPool = MongoPool("mongodb://localhost:27018/todos");
It can be called directly in the route handler:
@GenController(path: '/api/todos')
class TodoApi extends Controller {
@GetJson()
Future<List<TodoItem>> getAll(Context ctx) async {
final db = await mgoPool(ctx);
final coll = db.collection(todoColl);
return await coll.find().map(mongoSerializer.fromMap).toList();
}
}
Besides returning the Db
object directly, it also adds it to the current Context
's variables. This makes it possible to obtain the connection from anywhere in the route chain.
Since mgoPool
is an interceptor, it can be configured to be run using before
interceptor hook:'
@GenController(path: '/api/todos')
class TodoApi extends Controller {
@GetJson()
Future<List<TodoItem>> getAll(Context ctx) async {
final db = ctx.getVariable<Db>();
final coll = db.collection(todoColl);
return await coll.find().map(mongoSerializer.fromMap).toList();
}
Future<void> before(Context ctx) async {
await mgoPool(ctx);
}
}
TODO
In the next article, we will learn how to perform CRUD operations on MongoDb.
Basics
- Route handler
- Path matching
- Path parameters
- Query parameters
- Serving static files
- Cookies
- Controller
- Parameter binding
- Hot reload
Serialization
Forms
Sessions
Authentication
- Basic authentication
- Form authentication
- JSON authentication
- Authorization
- OAuth
- MongoDb
- PostgreSQL
- MySQL
- Establish connection
- ORM
- Server sent events (SSE)
- Websockets
- systemd
- Docker
- AppEngine