简体   繁体   中英

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM