Setting Up MongoDB with Koa.js
I’m building a Koa.js server and need to connect it to MongoDB to store and retrieve data. Here’s how to accomplish this in a few simple steps:
Step 1: Connect to the Database Before Initializing the Koa App
const initDB = require("./database")
initDB()
const app = new Koa()
Inside database.js
, import mongoose. Make sure to install mongoose using npm install --save mongoose
as well. Mongoose is an Object Data Modeling (ODM) library.
const mongoose = require("mongoose")
import { connectionString } from "./conf/app-config"
const initDB = () => {
mongoose.connect(connectionString)
mongoose.connection.once("open", () => {
console.log("Connected to the database")
})
mongoose.connection.on("error", console.error)
}
module.exports = initDB
Next, create the configuration for your connection string:
export const connectionString =
"mongodb+srv://" +
secret.mongodb.username +
":" +
secret.mongodb.password +
"@xxxxxx.mongodb.net/test?retryWrites=true&w=majority"
You can either run a local MongoDB instance or use MongoDB Atlas and host it on AWS cloud. You’ll find the connection string to include in your config file there.
Step 2: Create a Schema in Koa
For instance, let’s create a user schema inside /models/users.js
.
const mongoose = require("mongoose")
const Schema = mongoose.Schema
const UserSchema = new Schema({
username: String,
email: String,
picture: String,
})
module.exports = mongoose.model("User", UserSchema)
Step 3: Create a Service to Query the Data
Let’s say we have a /service/user.service.js
.
import User from "../models/users"
export const getUserFromDb = async username => {
const data = await User.findOne({ username })
return data
}
export const createUserInDb = async user => {
const newUser = new User(user)
await newUser.save()
return user
}
Step 4: Call the Service in the Koa Controller
For instance, let’s say we have a /controller/user.controller.js
.
import { getUserFromDb, createUserInDb } from '../service/user.service';
static async getUser(ctx) {
const user = await getUserFromDb(ctx.query.username);
ctx.body = user;
}
static async registerUser(ctx) {
const user = await createUserInDb(ctx.request.body);
ctx.body = user;
}
Finally, you can register the route using the controller. Now you should be able to see the data being stored in the database. Feel free to reach out if you have any questions.