相关文章推荐
豪爽的香槟  ·  双引号如何替换成单引号 - OSCHINA ...·  1 年前    · 
爱旅游的牙膏  ·  RN-第三方之-react-native-f ...·  1 年前    · 
着急的乌冬面  ·  java ...·  1 年前    · 
慷慨的枕头  ·  C# ...·  1 年前    · 
年轻有为的回锅肉  ·  一篇文章让你搞懂如何通过Nginx来解决跨域 ...·  2 年前    · 
Code  ›  How to Connect MongoDB to Node.js Using Mongoose
mongodb mongoose
https://www.topcoder.com/thrive/articles/how-to-connect-mongodb-to-node-js-using-mongoose
幸福的帽子
1 年前

August 24, 2022

How to Connect MongoDB to Node.js Using Mongoose

Thrive banner shape
Joseph Chege kimkimani

DURATION

8min

categories

Development
Back-End Development
How-To

Tags

MongoDB
NodeJS
JavaScript

share

Share on LinkedIn Share on Facebook Share on Twitter

COMPETITIVE PROGRAMMING AT TOPCODER

MongoDB is the most popular NoSQL database. MongoDB stores data in collections. The individual records in the collections are called documents, which have a key-value structure that is like JSON data. MongoDB is preferred because of its performance, flexibility, and scalability features.

What is Mongoose?

Mongoose is a promise-based Object Data Modeling (ODM) library for the Node.js framework. Mongoose simplifies how you interact with a MongoDB database. It allows you to create and model MongoDB schema. This way, you avoid complex writing of database queries/schemas. Mongoose gives you the ability to model the data you want to store in MongoDB.

This guide will help you understand how to connect MongoDB to Node.js using Mongoose.

Prerequisites

To continue with this guide, ensure

  • Node.js is installed on your computer.

  • MongoDB is installed on your computer or a cloud MongoDB Atlas account.

  • Basic knowledge of creating Node.js servers.

  • Postman is installed.

Setting the Node.js Mongoose Project

To create a Node.js project, run npm init -y in your desired folder. Then install the following packages:

  • Express - to create a Node.js HTTP server.

  • Mongoose - MongoDB ODM for Node.js

npm install express mongoose

Establish Mongoose MongoDB Node.js connection

To establish a connection to MongoDB using Mongoose, create a db.js file and connect Mongoose as follows:

  • Import the Mongoose library:
    const mongoose = require( 'mongoose' );

  • Create a connectDB as follows:

1
const connectDB = async () => {
  try {
    const conn = await mongoose.connect(`mongodb://localhost:27017/test`, {
      useNewUrlParser: true,
    console.log(`MongoDB Connected: {conn.connection.host}`);
  } catch (error) {
    console.error(error.message);
    process.exit(1);

The MongoDB used here is running locally. Thus, Mongoose will establish a connection to mongodb: //localhost:27017test , where test is your database name. Ensure you enter the correct URI that connects to either the locally installed MongoDB or cloud MongoDB Atlas.

Finally, export the connectDB function.

module.exports = connectDB ;

Create a server.js file to run this function as follows:

  • import Express and db.js file:

1
const express = require('express');
const connectDB = require('./db');
  • Add Express middleware and parser:

1
// express
const app = express();
//body parser
app.use(express.json());
  • Execute the connectDB() function:

1
//connect to database
connectDB();
  • Add server routes:

1
// routes
// We will add these routes later in this guide.
  • Run the application on a local host port:

1
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port {PORT}`));

To test this setup, run node server.js. This should log the following message if a connection to the database was established successfully.

image

Model a Schema Using Mongoose

A model defines a collection schema inside a MongoDB database. Create a model.js file and a Mongoose collection schema as follows:

1
const {
  Schema,
  model
} = require("mongoose");
const MySchema = new Schema({
  name: {
    type: String,
    required: true,
    maxlength: 50
  createdAt: {
    type: Date,
    default: Date.now,
const TaskModel = model("test", MySchema)
module.exports = TaskModel

Here, we are creating a MySchema function that executes the mongoose.Schema method. This method sets the schema that Mongoose will run to MongoDB. To create the schema, add the files that your document will have. In this case, we are adding two fields:

  • A name - As the above code inside, this field will be created as a string with a maxlength of fifty characters. required is set true to indicate that every document being created must have this field.

  • A createdAt field - Sets the time the document was created. It is executed as a date type created by default with the current date.

Add Data to the Database Using the Mongoose Schema

To add data to the database, create a controller.js file.

  • Import MySchema from the model file
    const Task = require( './model' );

  • Add a task to a task collection. This will define the POST route.

1
exports.createTask = async (req, res) => {
  try {
    // get the task from the body
    const taskData = await req.body;
    //create a new task then save
    await Task.create(taskData)
      .then((createdTask) => {
        if (!createdTask) return res.status(404)
          .json({
            success: false,
            message: "Task creation failed",
            error: "Unable get created task"
        res.status(201)
          .json({
            success: true,
            createdTask
      .catch((error) => {
        res.status(404)
          .json({
            success: false,
            error: error.message
  } catch (error) {
    res.status(500)
      .json({
        success: false,
        message: "Internal server error"

Retrieve All Tasks

Add this code to the controller.js file. This will define the GET route.

1
exports.createTask = async (req, res) => {
  try {
    // get the task from the body
    const taskData = await req.body;
    //create a new task then save
    await Task.create(taskData)
      .then((createdTask) => {
        if (!createdTask) return res.status(404)
          .json({
            success: false,
            message: "Task creation failed",
            error: "Unable get created task"
        res.status(201)
          .json({
            success: true,
            createdTask
      .catch((error) => {
        res.status(404)
          .json({
            success: false,
            error: error.message
  } catch (error) {
    res.status(500)
      .json({
        success: false,
        message: "Internal server error"
exports.getTasks = async (req, res) => {
  //get all the data in the model and return it as response
  try {
    Task.find()
      .then((allTasks) => {
        res.status(200)
          .json({
            success: true,
            allTasks
      .catch((error) => {
        res.status(404)
          .json({
            success: false,
            message: "Cant fined ",
            error
  } catch (error) {
    res.status(500)
      .json({
        success: false,
        message: "Internal server error",
        error: error.message

Create Routes

Create routes to execute the above controllers. Create a new file and call it routes.js and add the following code:

1
const router = require("express")
  .Router()
const controller = require('./controller')
router
  .post('/', controller.createTask)
  .get('/', controller.getTasks)
module.exports = router

Finally, execute these routes inside the server.js file.

1
const router = require('./routes')
app.use('/tasks', router)

Testing

To add a new task, send a POST request using postman as follows:

image

To retrieve the added tasks, send a GET request using postman as follows:

image

You can also view the added tasks by accessing your MongoDB database:

image

I hope you found this helpful!

Click to show preference!
Click to show preference!
D0A3FC91-EEC2-4529-BF7D-3B777D79E185 Chat on Discord

Recommended for you

Aggregations in MongoDB

Similar to SQL, MongoDB has aggregation pipelines and single aggregation methods to perform aggregation operat...
Read More E4627031-A283-4694-8843-C0F351FBA3F8

Schema Validation in MongoDB Atlas

Schema validation is a key concept while developing any backend application. Sometimes clients provide inputs ...
Read More E4627031-A283-4694-8843-C0F351FBA3F8

Storing Large Files in MongoDB Using GridFS

We often need to store files in our databases, but mongoDB doesn’t let you store any file larger than 16 Mb in...
Read More E4627031-A283-4694-8843-C0F351FBA3F8
 
推荐文章
豪爽的香槟  ·  双引号如何替换成单引号 - OSCHINA - 中文开源技术交流社区
1 年前
爱旅游的牙膏  ·  RN-第三方之-react-native-fs 文件下载、文本存储 - 简书
1 年前
着急的乌冬面  ·  java 账户挤下线提示_运用session来控制用户的异地登录被挤下线情况_顾煜的博客-CSDN博客
1 年前
慷慨的枕头  ·  C# WPF侧边栏导航菜单(Dropdown Menu) - 知乎
1 年前
年轻有为的回锅肉  ·  一篇文章让你搞懂如何通过Nginx来解决跨域问题 - 腾讯云开发者社区-腾讯云
2 年前
今天看啥   ·   Py中国   ·   codingpro   ·   小百科   ·   link之家   ·   卧龙AI搜索
删除内容请联系邮箱 2879853325@qq.com
Code - 代码工具平台
© 2024 ~ 沪ICP备11025650号