What is the best way to save Code Snippets in a MongoDB database?

I am looking to establish a Post route in order to store the code snippets typed by users into a MongoDB collection.

The schema I plan to use is as follows:

const newSnippetSchema= new mongoose.Schema({
     title:String,
     snippet:String
})

In short, my project involves developing a web application similar to platforms like codeSandbox or codepen where users can save and type code. I aim to send data in JSON format when the Post Route is activated.

Answer №1

Develop an HTTP POST web API.

const express = require('express')
const mongoose = require('mongoose')
const NewSnippetSchema = require('./models/newSnippetSchema')
const app = express()

mongoose.connect('mongodb://localhost/mydb', {
    useNewUrlParser: true, useUnifiedTopology: true
})

app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended:false }))

app.post('/newSnippet', async (req, res) => {
    await NewSnippetSchema.create({  title: req.body.title, snippet: req.body.snippet })
    res.redirect('/')
})

app.listen(process.env.PORT || 5000);

Answer №2

asyncHandler Function:

const asyncHandler = (fn) =>
  function handleAsync(...args) {
    const fnResult = fn(...args);
    const callback = args[args.length - 1];
    return Promise.resolve(fnResult).catch(callback);
  };
export default asyncHandler;

ErrorHandling Class:

class ErrorHandling extends Error {
  constructor(message, errorCode) {
    super(message);

    this.errorCode = errorCode;
    this.status = `${errorCode}`.startsWith('4') ? 'fail' : 'error';
    this.isHandled = true;

    Error.captureStackTrace(this, this.constructor);
  }
}

export default ErrorHandling;

DataController Code:

const dataController = asyncHandler(async (req, res, next) => {
   const { infoTitle, information } = req.body;

   if (!infoTitle || !information) {
     return next(new ErrorHandling('All fields are mandatory', 400));
   }

   const dataDocument = await Data.create(req.body);

   return res.status(201).json({
      status: 'success',
      dataDocument
   });
});

export default dataController;

Routing Code:

router.route('/data').post(dataController);

Answer №3

The role of the database in this scenario is negligible. The critical factor lies in how you present the information on your user interface through HTML rendering.

To safeguard data integrity, utilize the inherent HTML encoding function to encode snippets prior to database storage (for instance - swap all & with &). This precaution ensures secure data management.

Upon retrieval, remember to decode the content before displaying it on the UI for optimal presentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

HTML and CSS: Understanding DataTables Header Padding

http://jsfiddle.net/d1zqsayh/ (Strange issue not appearing on jsfiddle, very odd) When I modify the padding in the .css file at line 41 from 10px 18px; to 10px 17px;, I notice a difference in how the content is displayed on my screen in both Google Chrome ...

Issue with Helm Chart Bitnami: Replicaset not generating the desired database

Attempting to set up a database in a replicaset using helm, with the specified values in values.yaml: mongodb: architecture: replicaset auth: rootPassword: "admin" usernames: - "user1" passwords: - "pa ...

Custom Contract Serialization and Collections in JSON.NET

I am working on creating an IContractResolver to streamline my security management in a WebApi Project. My goal is: To serialize specific objects/properties based on dynamic conditions (such as the Role of the user calling the endpoint). So, I have deve ...

Troubleshooting Vercel and Express DELETE request cross-origin resource sharing problem

Currently, I am in the process of developing an API using Vercel and ExpressJS. The GET and POST endpoints are functioning properly, however, I encountered an issue with the DELETE endpoint. When attempting to access the endpoint from my client-side JavaSc ...

Increase the progress bar at regular intervals of x seconds

I am looking for a jQuery UI progress bar that will increase by x amount every x seconds. Once it reaches 100%, I need it to trigger a function to retrieve some content. Essentially, I need a timer-like feature. EDIT: Note that I do not require any code ...

What is the reason for an await statement in a server endpoint preventing other incoming requests from being processed?

I am currently testing two different versions of an endpoint. The first version looks like this: app.get('/order', async (req, res) => { console.log("OK") getPrintFile() }) The second version is as follows: app.get('/or ...

Using Reactjs to set state with a dynamically generated key-value pair

I have a dynamic object in props that I need to transfer to state @setState key: val values: another_key: value @props.data.option: @props.data.value Unfortunately, the above method does not work as expected. I have come up with an alternativ ...

Is there a way to alter the value of an Observable using Knockout and Typescript within its subscription?

Question: What is the best way to update the value of an Observable from within its subscription using Knockout and Typescript? I am currently in the process of refactoring some old Knockout code to use Typescript. While going through the code, I came acr ...

Issue occurred in module.js:341 while attempting to include android platform to ionic using command line

For my hybrid app development using the Ionic framework, I made sure to install all required dependencies like node.js and cordova. Following their Getting started guide, I reached step 3 which instructs running this command within the app directory: > ...

Retrieve Gridview properties using JavaScript

I need to adjust the font size of my gridview using JavaScript to make it more suitable for printing. What is the best way to change the font size specifically for a gridview using JavaScript? ...

Retrieve children of a specified node from a JSON object using JavaScript

I am in the process of developing a tool that can extract the Core Web Vitals metrics from a specified URL. By utilizing the API, I am able to retrieve a JSON object which can be accessed with JSONPath. I intend to utilize a forEach loop to populate the ...

What causes the appearance of 'GET/ 304 --' in my code? (vue.js, express)

While attempting to fetch data on the client-side using axios in vue.js, I encountered a server-side error with the code 'GET/ 304 --' The reason for this occurrence is unclear to me and I am unsure of how to troubleshoot or resolve it. If I re ...

The Node.js mongoose query is failing to retrieve any results

After hours of struggling, I am still stuck on this issue. Take a look at the code snippet below: router.route("/contact") .get(function(req,res){ var response = {}; Contact.find({},function(err,data){ if(err) { ...

Is there a method to manually generate a cookie for Internet Explorer using InnoSetup?

Is there a way to manually create a cookie in InnoSetup on behalf of a specific website, such as www.stackoverflow.com, similar to how JavaScript cookies are stored? Javascript cookie: function setCookie(cname,cvalue,exdays) { var d = new Date(); d.s ...

When the jQuery Div is moved to the right, it gradually shrinks in size, yet remains unchanged when

I have been making updates to this page, which you can view here. When you select "Let's Get Started" and then proceed with the right arrows, the divs smoothly move to the left without shrinking. However, when clicking on the back or left arrows, the ...

What is the method in MongoDb to retrieve the highest/lowest/average/count of a specific element within an embedded array?

I have a MongoDB collection that looks like the one below. I am looking to retrieve the min\max\avg\count of the xxx field within all documents where $match: { "Parsed.FileId": "421462559", "Parsed.MessageId": "123" } Please note that each ...

Leveraging NodeJS/express for efficient caching and optimizing 304 status codes

Upon reloading a website created with express, Safari displays a blank page (unlike Chrome) due to the 304 status code sent by the NodeJS server. How can this issue be resolved? While it could potentially be a problem with Safari itself, the fact that ot ...

Error encountered: The JSONP request to https://admin.typeform.com/app/embed/ID?jsoncallback=? was unsuccessful

I encountered an issue with the following error message: Error: JSONP request to https://admin.typeform.com/app/embed/id?jsoncallback=? Failed while trying to integrate a typeform into my next.js application. To embed the form, I am utilizing the react-ty ...

express req.session returns as undefined in Node.js

I'm really struggling with this issue. Despite everything I read about express session claiming that it should work seamlessly, I can't seem to make it function correctly. Here is my entire app configuration: app.configure -> app.set &apos ...

The integration of Vue.js with Firebase is causing an error stating "createUser is not a recognized function."

I am a beginner in Vue.js and I'm currently working on integrating Firebase with my Vue.js application. The app has two fields that I want to store in the Firebase database, but I keep encountering an error: <template> <div class="container ...