【问题标题】:How can I store Code Snippet in mongo db?如何将代码片段存储在 mongodb 中?
【发布时间】:2021-12-09 15:31:35
【问题描述】:

我想创建一个发布路由,这样我就可以将用户输入的代码 sn-ps 存储到 MongoDB 的集合中。

架构将如下所示:-

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

简而言之,我正在创建一个 web 应用程序,例如 codeSandbox 或 code-pen,我可以在其中保存用户保存或键入的代码...... 当 Post Route 被触发时,我想以 Json 格式发送数据

【问题讨论】:

    标签: javascript json mongodb express mongoose


    【解决方案1】:

    创建一个 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);
    

    【讨论】:

      【解决方案2】:

      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;
      

      App错误代码:

      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;
      

      控制器代码:

      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.route('/snippet').post(snippetController);
      

      【讨论】:

        【解决方案3】:

        数据库与此无关。如何存储它并不重要,重要的是如何在 UI 上以 HTML 表示形式呈现它。

        只需使用内置的 HTML 编码功能对代码 sn-p 进行编码,然后再将其存储到数据库中。(例如 - 将所有 & 编码为 & 之类的)。

        获取数据后,将其解码回来,然后在 UI 上呈现。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-01-31
          • 2010-09-21
          • 2021-12-17
          • 2016-04-30
          • 1970-01-01
          相关资源
          最近更新 更多