首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Node.js和角6在猫鼬中存储PDF文件

用Node.js和角6在猫鼬中存储PDF文件
EN

Stack Overflow用户
提问于 2019-05-31 07:41:58
回答 1查看 2.8K关注 0票数 1

我不得不在猫鼬的收集中存储大量的数据,它变得越来越大,而且很难处理。我想将PDF文件保存在某个地方,并将其链接到猫鼬集合中,我并不确定最佳的解决方案。因为大多数链接都是关于直接文件上传的,所以当我使用pdfmake库时,它会存储到收藏中。

这是我现在的型号

annual.js

代码语言:javascript
复制
customerReport: {
    createdBy: String,
    creationDate: String,
    hour: Number,
    waitingHour: Number,
    ccEmails: Array,
    sendToEmail: String,
    pdf: Schema.Types.Mixed,
    customerNotes: String
  },

这个pdf有完整的pdf内容在里面。

在我的路线中,当我最终保存和存储数据时

代码语言:javascript
复制
router.post('/stage/complete', (req, res, next) => {
  var completed = new AnnualStage({
    specs: req.body.specs,
    contactDetails: req.body.contactDetails,
    CalculationData: req.body.calculationData,
    customersData req.body.customersData
    customerReport: req.body.customerReport,
  });
  completed
    .save()
    .then(result => {
      res.status(200).json({
        result: result
      });
    })
    .catch(err => {
      res.status(500).json({
        message: err.message
      });
    });
});

所有前端由角6完成,生成所有数据和pdf并保存到mongo集合中。

您可以看到,我在路由中添加了GridFs,但是它将在哪里存储文件,以及它将如何链接回DB?

EN

回答 1

Stack Overflow用户

发布于 2019-05-31 08:11:04

免责声明:这应该是一个评论,但太长的评论。

您的代码有一个非常严重的标志,值得一提的是:

您应该在在任何情况下控制器中调用fs.readFileSync (或任何涉及I/O操作的同步方法)。

这将阻止--所有用户请求,直到文件是read.If --多个用户同时调用这个端点,他们中的大多数人的请求会延迟很长时间--

相反,您应该调用fs.readFile。使用async/awaitutil.promisify,代码看起来几乎相同,而不阻塞主线程:

代码语言:javascript
复制
const util = require('util');
const readFile = util.promisify(fs.readFile.bind.fs); // not really sure the bind is really needed tbh, maybe util.promisify(fs.readFile) works too
router.post('/stage/complete', async (req, res, next) => {
  var completed = new AnnualStage({
    specialRequest: req.body.specialRequest,
    contactDetails: req.body.contactDetails,
    requestData: req.body.requestData,
    customerRequests: req.body.customers,
    customerReport: req.body.customerReport,
  });
  completed.customerReport.pdf.data = await readFile(req.body.customerReport);
  completed.customerReport.pdf.contentType = 'application/pdf';
  completed
    .save()
    .then(result => {
      res.status(200).json({
        message: 'Handling POST request to /completed',
        result: result
      });
    })
    .catch(err => {
      res.status(500).json({
        message: err.message
      });
    });
});

此更改将严重改善您的帖子处理程序。

现在你的问题。我真的不确定你在问什么。你说:

您可以看到,我在路由中添加了GridFs,但是它将在哪里存储文件,以及它将如何链接回DB?

在代码段中没有对网格函数的引用。也许你忘了粘贴代码了?现在还不清楚AnnualStage.save()实际上是用芒果来储蓄的。它使用gridfs吗?

不清楚您的代码是否不工作,或者您是否询问您的解决方案是否足够好。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56390779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档