<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dev.Faanid</title>
    <description>The latest articles on DEV Community by Dev.Faanid (@faanid).</description>
    <link>https://dev.to/faanid</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1117748%2F378650aa-6fe7-496a-ac7a-1d302dbc3998.jpg</url>
      <title>DEV Community: Dev.Faanid</title>
      <link>https://dev.to/faanid</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/faanid"/>
    <language>en</language>
    <item>
      <title>Building a Simple Task Management API with Node.js, Express and MongoDB</title>
      <dc:creator>Dev.Faanid</dc:creator>
      <pubDate>Wed, 10 Jan 2024 09:57:34 +0000</pubDate>
      <link>https://dev.to/faanid/building-a-simple-task-management-api-with-nodejs-express-and-mongodb-3bjk</link>
      <guid>https://dev.to/faanid/building-a-simple-task-management-api-with-nodejs-express-and-mongodb-3bjk</guid>
      <description>&lt;h2&gt;
  
  
  Introdoction
&lt;/h2&gt;

&lt;p&gt;Task management is a crucial aspect of many applications and building a robust backend to handle tasks can streamline your development process. In this article, we'll create a simple Task Management API using Node.js, Express, and MongoDB. The code is organized into three main files: &lt;code&gt;server.js&lt;/code&gt;, &lt;code&gt;connectDB.js&lt;/code&gt;, and &lt;code&gt;taskModel.js&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Setting up the Express Server
&lt;/h2&gt;

&lt;p&gt;Let's start by setting up our Express server in &lt;code&gt;server.js&lt;/code&gt;. This file acts as the entry point for our application.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// server.js

const dotenv = require("dotenv").config();
const express = require("express");
const connectDB = require("./config/connectDB");
const mongoose = require("mongoose");
const Task = require("./model/taskModel");

const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// Routes
app.get("/", (req, res) =&amp;gt; {
  res.send("Home page");
});

// Create a Task
app.post("/api/tasks", async (req, res) =&amp;gt; {
  try {
    const task = await Task.create(req.body);
    res.json(task);
  } catch (error) {
    res.status(500).json({ msg: error.message });
  }
});

const PORT = process.env.PORT || 5000;

const startServer = async () =&amp;gt; {
  try {
    await connectDB();
    app.listen(PORT, () =&amp;gt; {
      console.log(`Server running on port ${PORT}`);
    });
  } catch (error) {
    console.log(error);
  }
};

startServer();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code snippet, we've set up an Express server, defined a simple route for the home page, and created an API endpoint for adding tasks.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Connecting to MongoDB
&lt;/h2&gt;

&lt;p&gt;The &lt;code&gt;connectDB.js&lt;/code&gt; file is responsible for establishing a connection to our MongoDB database using Mongoose.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// connectDB.js

const mongoose = require("mongoose");

const connectDB = async () =&amp;gt; {
  try {
    const connect = await mongoose.connect(process.env.MONGO_URI);
    console.log(`MongoDB Connected`);
  } catch (error) {
    console.log(error);
    process.exit(1);
  }
};

module.exports = connectDB;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This module exports a function that connects to MongoDB using the URI specified in the &lt;code&gt;MONGO_URI&lt;/code&gt; environment variable.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Creating the Task Model
&lt;/h2&gt;

&lt;p&gt;In &lt;code&gt;taskModel.js&lt;/code&gt;, we define the Mongoose schema for our tasks and create a model based on that schema.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
// taskModel.js

const mongoose = require("mongoose");

const taskSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please add a task"],
    },
    completed: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  {
    timestamps: true,
  }
);

const Task = mongoose.model("Task", taskSchema);

module.exports = Task;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This module exports the &lt;code&gt;Task&lt;/code&gt; model, which represents the structure of our task documents in the MongoDB collection.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;Adding more features&lt;/em&gt; &lt;br&gt;
&lt;em&gt;updating and&lt;/em&gt;&lt;br&gt;
&lt;em&gt;deleting tasks,&lt;/em&gt;&lt;br&gt;
&lt;em&gt;implementing,&lt;/em&gt;&lt;br&gt;
&lt;em&gt;user authentication...&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

</description>
    </item>
    <item>
      <title>Next.js API endpoint with MongoDB</title>
      <dc:creator>Dev.Faanid</dc:creator>
      <pubDate>Sun, 16 Jul 2023 15:37:41 +0000</pubDate>
      <link>https://dev.to/faanid/nextjs-api-endpoint-with-mongodb-33h2</link>
      <guid>https://dev.to/faanid/nextjs-api-endpoint-with-mongodb-33h2</guid>
      <description>&lt;p&gt;Next.js supports multiple ways to get data. We can create &lt;br&gt;
&lt;strong&gt;&lt;a href="https://nextjs.org/docs/api-routes/introduction"&gt;API endpoints&lt;/a&gt;&lt;/strong&gt;, get data by running &lt;strong&gt;&lt;a href="https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering"&gt;server-side rendered functions&lt;/a&gt;&lt;/strong&gt; for a particular page, or even &lt;strong&gt;&lt;a href="https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation"&gt;generate static pages&lt;/a&gt;&lt;/strong&gt; by getting our data at build-time. &lt;/p&gt;
&lt;h2&gt;
  
  
  Example 1
&lt;/h2&gt;

&lt;p&gt;The first example we'll look at is building and exposing an API endpoint in our Next.js application. To create a new API endpoint route, we will first need to create an **api **directory in our **pages **directory, and then every file we create in this **api **directory will be treated as an individual API endpoint.&lt;/p&gt;

&lt;p&gt;Let's go ahead and create the &lt;strong&gt;api **directory and a new file in this **directory **called **movies.js&lt;/strong&gt; . This endpoint will return a list of 20 movies from our MongoDB database. The implementation for this route is as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import clientPromise from "../../lib/mongodb";

export default async (req, res) =&amp;gt; {
   try {
       const client = await clientPromise;
       const db = client.db("sample_mflix");

       const movies = await db
           .collection("movies")
           .find({})
           .sort({ metacritic: -1 })
           .limit(10)
           .toArray();

       res.json(movies);
   } catch (e) {
       console.error(e);
   }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To explain what is going on here, we'll start with the import statement. We are importing our &lt;code&gt;clientPromise&lt;/code&gt;method from the &lt;code&gt;lib/mongodb&lt;/code&gt; file. This file contains all the instructions on how to connect to our MongoDB Atlas cluster. Additionally, within this file we cache the instance of our connection so that subsequent requests do not have to reconnect to the cluster. They can use the existing connection. All of this is handled for you!&lt;/p&gt;

&lt;p&gt;Next, our API route handler has the signature of &lt;code&gt;export default async (req, res)&lt;/code&gt;. If you're familiar with &lt;br&gt;
Express.js&lt;br&gt;
, this should look very familiar. This is the function that gets executed when the &lt;code&gt;localhost:3000/api/movies&lt;/code&gt; route is called. We capture the request via &lt;code&gt;req&lt;/code&gt;and return the response via the &lt;code&gt;res&lt;/code&gt;object.&lt;br&gt;
Our handler function implementation calls the &lt;code&gt;clientPromise&lt;/code&gt;function to get the instance of our MongoDB database. Next, we execute a MongoDB query using the &lt;br&gt;
&lt;strong&gt;&lt;a href="https://docs.mongodb.com/drivers/node/?_ga=2.62434732.1249872732.1689513829-1061523893.1689513828"&gt;MongoDB Node.js Driver&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
 to get the top 20 movies out of our movies collection based on their **metacritic **rating sorted in descending order.&lt;br&gt;
Finally, we call the &lt;code&gt;res.json&lt;/code&gt; method and pass in our array of movies. This serves our movies in JSON format to our browser. If we navigate to &lt;code&gt;localhost:3000/api/movies&lt;/code&gt;.&lt;br&gt;
we'll see a result that looks like this:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rtP9q5sw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j47v3ccd1gtrrf2ei3v3.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rtP9q5sw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j47v3ccd1gtrrf2ei3v3.jpg" alt="Image description" width="525" height="390"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Add additional API routes by creating additional files in the &lt;code&gt;api&lt;/code&gt;directory:
&lt;/h2&gt;

&lt;p&gt;To give you some pointers, you'll use &lt;strong&gt;&lt;a href="https://nextjs.org/docs/api-routes/dynamic-api-routes"&gt;Next.js Dynamic API Routes&lt;/a&gt;&lt;/strong&gt;&lt;br&gt;
 to capture the &lt;code&gt;id&lt;/code&gt;. So, if a user calls &lt;code&gt;http://localhost:3000/api/movies/573a1394f29313caabcdfa3e&lt;/code&gt;, the movie that should be returned is &lt;strong&gt;Seven Samurai&lt;/strong&gt;. Another tip, the &lt;code&gt;_id&lt;/code&gt; property for the &lt;code&gt;sample_my-app&lt;/code&gt; database in MongoDB is stored as an ObjectID, so you'll have to convert the string to an ObjectID. &lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>mongodb</category>
      <category>api</category>
    </item>
  </channel>
</rss>
