Setup MongoDB with Koa.js
I’m building a Koa.js server and need to connect to MongoDB to store and retrieve data. Here is how to do it with some simple steps:
Step 1: Connect the database before Koa app initialised
const initDB = require('./database');
initDB();
const app = new Koa();
Inside the database.js, import mongoose. You will need to npm install -save mongoose as well. It is an Object Data Modeling (ODM) library.
const mongoose = require('mongoose');
import { connexionString } from './conf/app-config';
const initDB = () => {
mongoose.connect(connexionString);
mongoose.connection.once('open', () => {
console.log('connected to database');
});
mongoose.connection.on('error', console.error);
}
module.exports = initDB;
And the create the config of your connection string:
export const connexionString = 'mongodb+srv://'+secret.mongodb.username+':'+secret.mongodb.password+'@xxxxxx.mongodb.net/test?retryWrites=true&w=majority';
You may run a local mongodb or you can use MongoDB Altas and run it on AWS cloud. Then you would get the connection string to put inside your config file.
Step 2: Create a schema in Koa
For example, we 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
For example, we have a /service/user.service.js
import User from '../models/users';
export const getUserFromDb = async (username) => {
const data = await User.findOne({username: username})
return data;
};
export const createUserInDb = async (user) => {
var newUser = new User(user);
newUser.save();
return user; }
Step 4: Call the service in Koa controller
For example, we have a /controller/user.controller.js
import { getUserFromDb } from '../service/user.service';
import { 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 and you can see the data being stored in the database. Let me know if you have any questions.
Originally published at https://victorleungtw.com on November 3, 2019.