You can use any database with Deno as long as there’s a controller for it. Explore how to set up MongoDB in a Deno application.

Deno is a simple and secure runtime for JavaScript that supports and configures TypeScript by default. MongoDB is a cross-platform document-oriented database program that is widely used by developers. In this article, we will learn how to integrate MongoDB into our Deno application.

Prerequisites

  • Familiarity with TypeScript
  • VS Code, or any code editor installed on your development machine.
  • Basic knowledge of MongoDB.
  • POSTMAN installed on local machine.

Before we start, make sure you have Deno installed on your local machine. If you’re using a Mac and you don’t yet have it installed, open up your terminal and run this command:

brew install deno

If you are using a Windows machine, you can install it by running this command on your terminal:

iwr https://deno.land/x/install/install.ps1 -useb | iex

Or, if you have Chocolatey installed, you could run:

choco install deno

Getting started

We will start by creating a server.js file and then set up our Deno server. Since there is no package.json file like we have in Node.js, Deno uses modules reference by URLs or file paths.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";
const app = new Application();
const router = new Router();
const PORT = 3000;
router
  .get("/", (ctx) => {
    ctx.response.body = "This is the home route";
  });
app.use(router.routes());
app.use(router.allowedMethods());
app.listen({ port: PORT });

We are using Oak to run our server. Oak is a Deno middleware framework for HTTP servers, and it includes a router middleware as well.

We can now run deno run --allow-net server.ts on our terminal to serve our application. Due to Deno’s security, we need to add the --allow-net to run a server. We can look up the application on our browser on localhost:8000.

Now that our server is up and running, we can start setting up MongoDB in our application. Create a db.js file, which is where we will set up our DB config:

// import the package from url
import { init, MongoClient } from "https://deno.land/x/mongo@v0.12.1/mod.ts";
// Intialize the plugin
await init();
// Create client
const client = new MongoClient();
// Connect to mongodb
client.connectWithUri("mongodb://localhost:27017");
// Give your database a name
const dbname: string = "denoMongoApp";
const db = client.database(dbname);
// Declare the mongodb collections here. Here we are using only one collection (i.e user).
// Defining schema interface
interface UserSchema {
  _id: { $oid: string };
  name: string;
  email: string;
  phone: string;
}
const User = db.collection<UserSchema>("user");
export { db, User };

#deno #mongodb #database #web-development #developer

How to Integrate MongoDB Into Deno Application
1.90 GEEK