简体   繁体   English

如何在 mongo db 中存储代码片段?

[英]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.我想创建一个 post 路由,以便我可以将用户键入的代码片段存储到 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简而言之,我正在创建一个像 codeSandbox 或 code-pen 这样的网络应用程序,我可以在其中保存用户已保存或输入的代码......我想在触发 Post Route 时以 Json 格式发送数据

Create a http post web api.创建一个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: catchAsync 代码:

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.您如何存储它并不重要,重要的是如何在 UI 上的 HTML 表示中呈现它。

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).只需使用内置的 HTML 编码功能在将代码片段存储到数据库之前对其进行编码。(例如 - 将所有&编码为&类似的东西)。

After fetching the data, decode it back before rendering it on the UI.获取数据后,将其解码,然后再将其呈现在 UI 上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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