Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
How can I store Code Snippet in mongo db?

I want to create A post route So I Can store the User Typed code snippets into the collection in MongoDB.

the schema would look like this:-

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

to be brief I am working on creating a web app like codeSandbox or code-pen where I can save the code user has saved or typed.... I want to send data in Json format when Post Route is triggered

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Create a 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);
about 4 years ago · Juan Pablo Isaza Denunciar

0

catchAsync Code:

const catchAsync = (fn) =>
  function asyncUtilWrap(...args) {
    const fnReturn = fn(...args);
    const next = args[args.length - 1];
    return Promise.resolve(fnReturn).catch(next);
  };
export default catchAsync;

AppError Code:

class AppError extends Error {
  constructor(message, statusCode) {
    super(message);

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

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

export default AppError;

Controller Code:

const snippetController = catchAsync(async (req, res, next) => {
   const { title, snippet } = req.body;

   if (!title || !snippt) {
     return next(new AppError('All fields are required', 400));
   }

   const snippetDoc = await Snippet.create(req.body);

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

export default snippetController;

Router Code:

router.route('/snippet').post(snippetController);
about 4 years ago · Juan Pablo Isaza Denunciar

0

The database has nothing to do with this. It doesn't matter how you store it, what matters is how render it in your HTML representation on the UI.

Just use the built-in HTML encoding function to encode the code snippet before storing it in the database.(eg - encode all & as & something like this).

After fetching the data, decode it back before rendering it on the UI.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda