0

Is there any easy way to connect my koa.js backend with mongodb

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Aug 24 '22 at 18:53

1 Answers1

0

This is the way I implemented. There is some issue in connecting with mongodb. https://github.com/thiva99/koa_Backend

package.json package.json file

{
  "name": "backend",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
   
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^2.0.18"
  },
  "dependencies": {
    "bcrypt": "^5.0.1",
    "bcryptjs": "^2.4.3",
    "dotenv": "^16.0.1",
    "jsonwebtoken": "^8.5.1",
    "koa": "^2.13.4",
    "koa-bodyparser": "^4.3.0",
    "koa-cors": "0.0.16",
    "koa-json": "^2.0.2",
    "koa-router": "^10.1.1",
    "mongoose": "^6.4.0"
  }
}

**server.js** this is the server.js file

const koa = require('koa');
const json = require("koa-json");
const cors = require("koa-cors");
const bodyparser = require('koa-bodyparser');
const mongoose = require("mongoose");
require('dotenv').config();
const PORT = 8000;
const app = new koa();
app.use(bodyparser());
app.use(json());
app.use(cors());

//routes
const userRouter = require('./routes/userRouter');
app.use(userRouter.routes()).use(userRouter.allowedMethods());

//connecting to db 
const db = mongoose.connection;
const dbUpdate = {
    useNewUrlParser: true,
    useUnifiedTopology: true,
};
mongoose.connect(process.env.DB_URL, dbUpdate);

db.on('error', (err) => console.log("Error DB Not Connected" + err));
db.on('connected', () => console.log("DB Connected"));
db.on('diconnected', () => console.log("DB disconnected"));
db.on('open', () => console.log("Connection Mode! "));

//Server listening port
app.listen(PORT, () => {
    console.log("Äpp is Started on port: " + PORT);
})

**routes** *userRouter.js*

const koaRouter = require('koa-router');
const { register, login,getAllUserDetails} = require('../api/userApi');
const userRouter = new koaRouter(({ prefix: '/user' }));

userRouter.get("/all", getAllUserDetails);
userRouter.post('/register', register);
userRouter.get('/login', login); 

module.exports = userRouter;

**model** *userModel.js* 

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema(
    {
        name: {
            type: String,
            require: true,
        },
        email: {
            type: String,
            unique: true,
            require: true,
        },
        password: {
            type: String,
            require: true,
        },
        role: {
            type: Number,
            default: 0,
        },
    }
);
const User = mongoose.model('users',userSchema);
module.exports =User;

**api** *userApi.js*

require("dotenv").config();
const User = require("../model/userModel");

let message, status;

const register = async (ctx) => {
  try {
    const user = ctx.request.body;
    const { name, email, password, role } = user;
    const newUser = new User({
      name,
      email,
      password,
      role,
    });
    await newUser.save();
    message = "Registartion Success!";
    status = 200;
  } catch (error) {
    console.log(error);
    message = error;
    status = 500;
  }
  ctx.body = message;
  ctx.status = status;
};
const login = async (ctx) => {
  try {
    const { email, password } = ctx.request.body;
    const user = await User.findOne({
      $and: [{ email: { $eq: email } }, { password: { $eq: password } }],
    });
    if (!user) {
      ctx.body = "User not fount";
      ctx.status = 400;
    } else {
        ctx.body = user;
        ctx.status=200;
    }
  } catch (error) {
    message = error.message;
    status = 500;
  }
};

const getAllUserDetails = async (ctx) => {
  try {
    const users = await User.find();
    message = users;
    status = 200;
  } catch (error) {
    message = error.message;
    status = 500;
  }
  ctx.body = message;
  ctx.status = status;
};
// const getMyDetails = async (ctx) => {
//   try {
//     const uid = await ctx.request.user.id;

//     const user = await User.findById(uid);
//     status = 200;
//     message = user;
//   } catch (error) {
//     message = error.message;
//     status = 500;
//   }
//   ctx.body = message;
//   ctx.status = status;
// };

// const getAllUserDetails = async (ctx) => {
//   try {
//     const users = await User.find();
//     message = users;
//     status = 200;
//   } catch (error) {
//     message = error.message;
//     status = 500;
//   }
//   ctx.body = message;
//   ctx.status = status;
// };

// const deleteMyAccount = async (ctx) => {
//   try {
//     await User.findByIdAndDelete(ctx.request.user.id);
//     message = "Delete Successfull";
//     status = 200;
//   } catch (error) {
//     message = error.message;
//     status = 500;
//   }
//   ctx.body = message;
//   ctx.status = status;
// };

// const deleteUserAccount = async (ctx) => {
//   try {
//     const uid = ctx.request.params.uid;
//     await User.findByIdAndDelete(uid);
//     message = "Delete Successfull";
//     status = 200;
//   } catch (error) {
//     message = error.message;
//     status = 500;
//   }
//   ctx.body = message;
//   ctx.status = status;
// };

// const updateUserAccount = async (ctx) => {
//   try {
//     const uid = ctx.request.params.uid;
//     const { role } = ctx.request.body;
//     await User.findByIdAndUpdate(uid, { role: role });
//     message = "Update Successfull";
//     status = 200;
//   } catch (error) {
//     message = error.message;
//     status = 500;
//   }
//   ctx.body = message;
//   ctx.status = status;
// };

module.exports = {
  register,
  login,
  getAllUserDetails,
//   getMyDetails,
//   getAllUserDetails,
//   deleteMyAccount,
//   deleteUserAccount,
//   updateUserAccount,
};