Skip to content

MongoDb: Establish connection

Ravi Teja Gudapati edited this page Jan 3, 2019 · 5 revisions

Without using interceptor

Packages Used

  • mongo-dart : MongoDB client for Dart.

Establish connection

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();
    ...
  }
}

Using interceptor

Packages Used

  • mongo-dart : MongoDB client for Dart.
  • jaguar_mongo : mongo interceptor for Jaguar.

Establish connection

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);
  }
}

References

TODO

What's next?

In the next article, we will learn how to perform CRUD operations on MongoDb.

Basics

Serialization

Forms

Sessions

Authentication

  • Basic authentication
  • Form authentication
  • JSON authentication
  • Authorization
  • OAuth

Database

Security

Real time

  • Server sent events (SSE)
  • Websockets

Deployment

  • systemd
  • Docker
  • AppEngine

API Documentation

Clone this wiki locally