Home > Mobile >  How can I store Code Snippet in mongo db?
How can I store Code Snippet in mongo db?

Time:10-24

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

CodePudding user response:

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);

CodePudding user response:

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);
  • Related