<?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>Forem: Harsh Kanodiya</title>
    <description>The latest articles on Forem by Harsh Kanodiya (@might_be_harsh).</description>
    <link>https://forem.com/might_be_harsh</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%2F734019%2Fcafbabfe-833d-4574-9dfc-051a69c29046.png</url>
      <title>Forem: Harsh Kanodiya</title>
      <link>https://forem.com/might_be_harsh</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/might_be_harsh"/>
    <language>en</language>
    <item>
      <title>Using MedusaJS with MongoDB</title>
      <dc:creator>Harsh Kanodiya</dc:creator>
      <pubDate>Tue, 02 May 2023 12:39:43 +0000</pubDate>
      <link>https://forem.com/might_be_harsh/using-medusajs-with-mongodb-10a4</link>
      <guid>https://forem.com/might_be_harsh/using-medusajs-with-mongodb-10a4</guid>
      <description>&lt;p&gt;A tutorial on how to integrate MedusaJS with MongoDB to create a robust and scalable database-driven application&lt;br&gt;
MedusaJS is a Node.js framework for building scalable and modular applications. One of the key features of MedusaJS is its ability to work seamlessly with various databases, including MongoDB. In this tutorial, we will walk through the steps required to integrate MedusaJS with MongoDB to create a robust and scalable database-driven application.&lt;/p&gt;

&lt;p&gt;Prerequisites&lt;/p&gt;

&lt;p&gt;Before we get started, you’ll need to have the following installed on your computer:&lt;/p&gt;

&lt;p&gt;Node.js (version 14 or higher)&lt;br&gt;
MongoDB (version 4 or higher)&lt;br&gt;
Creating a new MedusaJS project&lt;/p&gt;

&lt;p&gt;First, let’s create a new MedusaJS project. Open your terminal or command prompt and run the following commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir my-medusa-project
cd my-medusa-project
npm init -y
npm install --save medusa
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a new directory called “my-medusa-project”, initialize a new npm package, and install the MedusaJS framework.&lt;/p&gt;

&lt;p&gt;Connecting to MongoDB&lt;/p&gt;

&lt;p&gt;Next, we need to set up a connection to our MongoDB database. Create a new file called “database.js” in the root directory of your project and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose');

const connect = async () =&amp;gt; {
  try {
    await mongoose.connect('mongodb://localhost/my-database', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('Connected to MongoDB');
  } catch (error) {
    console.error('Error connecting to MongoDB:', error);
  }
};

module.exports = {
  connect,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code sets up a connection to a MongoDB database called “my-database” running on your local machine. Make sure to replace “my-database” with the name of your own MongoDB database. We’re using the Mongoose library to interact with MongoDB, which provides a simple and intuitive way to work with MongoDB from Node.js.&lt;/p&gt;

&lt;p&gt;To use this code, we need to call the connect() function somewhere in our application. We can do this in the main file of our project (e.g. "index.js"):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { connect } = require('./database');

connect();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will connect to the MongoDB database when we start our application.&lt;/p&gt;

&lt;p&gt;Defining a schema and model&lt;/p&gt;

&lt;p&gt;Now that we have a connection to our MongoDB database, let’s define a schema and model for our data. Create a new file called “product.js” in a new directory called “models” and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require('mongoose');

const schema = new mongoose.Schema({
  name: { type: String, required: true },
  price: { type: Number, required: true },
});

const model = mongoose.model('Product', schema);

module.exports = {
  schema,
  model,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code defines a schema for a product, with a name and a price. We’re also creating a model for this schema using Mongoose’s model() function. The model() function takes two arguments: the name of the collection in the database (which is "products" by default), and the schema we just defined.&lt;/p&gt;

&lt;p&gt;Using the model in our application&lt;/p&gt;

&lt;p&gt;Now that we have a model for our product data, let’s use it in our application. Create a new file called “products.js” in a new directory called “routes” and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { Router } = require('medusa');
const { model: Product } = require('../models/product');

const router = new Router();

router.get('/products', async(req, res) =&amp;gt; {
try {
const products = await Product.find();
res.json(products);
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal server error' });
}
});

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code defines a new route that handles GET requests to “/products”. When a user makes a request to this route, the function defined in the second argument will be called. This function uses the find() method on our Product model to retrieve all products from the database, and returns them as a JSON response.&lt;/p&gt;

&lt;p&gt;We can now import this route in our main file (“index.js”) and add it to 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;const { Medusa } = require('medusa');
const { connect } = require('./database');
const productRoutes = require('./routes/products');

const app = new Medusa();

app.use(productRoutes);

connect()
  .then(() =&amp;gt; {
    app.listen(3000, () =&amp;gt; {
      console.log('Server listening on port 3000');
    });
  })
  .catch((error) =&amp;gt; {
    console.error('Error starting server:', error);
  });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code creates a new Medusa application, sets up our product routes, and starts listening on port 3000. The connect() function is called to connect to the MongoDB database before starting the server.&lt;/p&gt;

&lt;p&gt;Testing the application&lt;/p&gt;

&lt;p&gt;Finally, let’s test our application to make sure everything is working as expected. Open your terminal or command prompt and run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install --save-dev supertest
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will install the supertest library, which we can use to write automated tests for our application.&lt;/p&gt;

&lt;p&gt;Create a new file called “products.test.js” in a new directory called “tests” and add the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const request = require('supertest');
const { Medusa } = require('medusa');
const { connect } = require('../database');
const productRoutes = require('../routes/products');

describe('Products API', () =&amp;gt; {
  let app;

  beforeAll(async () =&amp;gt; {
    await connect();
    app = new Medusa();
    app.use(productRoutes);
  });

  afterAll(async () =&amp;gt; {
    await new Promise((resolve) =&amp;gt; setTimeout(resolve, 500)); // workaround for jest open handle error
    await app.close();
  });

  describe('GET /products', () =&amp;gt; {
    it('returns all products', async () =&amp;gt; {
      const response = await request(app).get('/products');
      expect(response.status).toBe(200);
      expect(response.body).toEqual([]);
    });
  });
});

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

&lt;/div&gt;



&lt;p&gt;This code defines a test suite for our product routes. The beforeAll() function is called before any tests are run, and sets up our Medusa application with our product routes. The afterAll() function is called after all tests are run, and closes the application. The describe() and it() functions are used to define test cases.&lt;/p&gt;

&lt;p&gt;Run the tests by running the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx jest tests/products.test.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will run the tests and output the results in your terminal or command prompt.&lt;/p&gt;

&lt;p&gt;Conclusion&lt;/p&gt;

&lt;p&gt;In this tutorial, we walked through the steps required to integrate MedusaJS with MongoDB to create a robust and scalable database-driven application. We set up a connection to MongoDB, defined a schema and model for our data, and used that model in our application to handle CRUD operations. We also wrote automated tests to ensure our application is working as expected. With this knowledge, you should be able to build your own database-driven applications using MedusaJS and MongoDB.&lt;/p&gt;

</description>
      <category>medusa</category>
      <category>mongodb</category>
      <category>javascript</category>
      <category>node</category>
    </item>
  </channel>
</rss>
