I have already done connect MongoDB using mongodbClient. but I want to connect MongoDB through mongoose.
This is my current configuration
this is Db Connection import { MongoClient } from 'mongodb';
const URI = 'xxxxxxxxxxxxxxxxxxxxx';
const mongoClient = new MongoClient(URI);
mongoClient.connect().then(() => {
console.log("Db connected");
});
export default mongoClient;
Server configuration start here it will use to call middleware
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import postRouter from './postRouter.js';
import './db/mongoClient.js'
const app = new Koa();
app.use(bodyParser());
app.use(postRouter.routes())
.use(postRouter.allowedMethods());
app.use(ctx => {
ctx.response.set('Access-Control-Allow-Origin', 'http://localhost:1234');
ctx.response.set('Access-Control-Allow-Origin', 'GET, POST, OPTIONS, PUT, DELETE');
ctx.response.set('Access-Control-Allow-Origin', '*');
next();
});
app.use((ctx) => {
ctx.body = 'Resource you are looking for was not found';
ctx.status = 404;
})
app.listen(3000);
console.log("App is running on port 3000");
Controller configuration starts here,
import { ObjectId } from "mongodb";
import mongoClient from "./db/mongoClient.js";
const collection = mongoClient.db('posts').collection('post');
const save = async (post) => {
const inserted = await collection.insertOne({ ...post });
return inserted.insertedId;
};
const getAll = async () => {
const cursor = await collection.find();
const posts = [];
await cursor.forEach(doc => {
const { _id: id, title, description, user, posted } = doc;
posts.push({ id, title, description, user, posted });
});
return posts;
};
const getByDataId = async (findId) => {
const doc = await collection.findOne({ _id: ObjectId(findId) });
const { _id: id, title, description, user, posted } = doc;
return { id, title, description, user, posted };
};
export { save, getAll, getByDataId };
CourseModels
const mongoose = require('mongoose');
const CourseScheema = new mongoose.Schema({
courseName:
{
type: String,
require: true,
},
coursefee:
{
type: Number,
require: true,
},
student:
[{
type: mongoose.Schema.Types.ObjectId,
require: false,
ref: "students"
}],
});
const Course = mongoose.model("course", CourseScheema);
module.exports = Course;
Router-course
const KoaRouter = require('koa-router');
const { addCourse, getcourse, updatecourse, deleteCourse } = require('../controller/courseController');
const router = new KoaRouter({ prefix: "/course" })
router.post("/add", addCourse);
router.put("/:courseId", updatecourse);
router.delete("/:courseId", deleteCourse);
router.get("/", getcourse);
module.exports = router;
Controller- course
const Course = require("../models/courseModel");
const addCourse = async (ctx) => {
try {
const { courseName, coursefee, student } = ctx.request.body;
const course = await Course.create({
courseName: courseName,
coursefee: coursefee,
student: student,
});
return (ctx.body = { course: course });
} catch {
return (ctx.body = { message: error.message });
}
}
//get function
const getcourse = async (ctx) => {
try {
const courses = await Course.find({});
return (ctx.body = { courses: courses })
} catch (error) {
return (ctx.body = { message: error.message })
}
}
//update
const updatecourse = async (ctx) => {
try {
const courseId = ctx.params.courseId;
const { courseName, coursefee, student } = ctx.request.body;
const course = await Course.findByIdAndUpdate(courseId, {
courseName: courseName,
coursefee: coursefee,
student: student
});
return (ctx.body = course);
} catch (error) {
return (ctx.body = { message: error.message })
}
};
//delete function
const deleteCourse = async (ctx) => {
try {
const courseId = ctx.params.courseId;
const course = await Course.findByIdAndDelete(courseId);
return (ctx.body = course);
} catch (error) {
return (ctx.body = { message: error.message })
}
}
module.exports = {
addCourse,
getcourse,
updatecourse,
deleteCourse,
}
Package.json
{
"name": "backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev" : "nodemon index.js",
"start": "node index.js"
},
"author": "shanu",
"license": "ISC",
"dependencies": {
"@koa/cors": "^3.3.0",
"dotenv": "^16.0.1",
"koa": "^2.13.4",
"koa-bodyparser": "^4.3.0",
"koa-json": "^2.0.2",
"koa-router": "^10.1.1",
"mongoose": "^6.4.0"
},
"devDependencies": {
"nodemon": "^2.0.18"
}
}