mongodb - 如何使用nestJS将文件上传到mongoose上的mongodb?
问题描述
你好请问有人知道如何使用nestJS将文件上传到MongoDB(猫鼬)吗?
我已经能够@Post 将文件上传到我的nestJS projet 和@Get,但知道我想使用mongoose 发布到mongodb,请帮助
解决方案
我不建议将图像存储在您的数据库中,但您可以这样做:
async function saveFile(file: Express.Multer.File){
//Convert the file to base64 string
const fileB64 = file.buffer.toString('base64')
//userModel is a mongoose model
//Store the string
await this.userModel.create({file: fileB64})
}
async function getFile(userId: string){
//Get user from database
const user = await this.userModel.findOne({_id: userId}).lean()
if(!user) throw new NotFoundException('User not found')
const file = user.file
//Convert the string to buffer
return Buffer.from(file, 'base64')
}
首先,您必须将该文件转换为具有 base64 编码的字符串,然后您可以使用 create 方法将该字符串保存在数据库中或更新文档。
如果您想获取该文件,只需在数据库中搜索该信息,然后将字符串转换为缓冲区并返回它。
就像我之前说的,我不建议这样做,最好将缓冲区上传到 s3 并将链接保存在数据库中。
推荐阅读
- javascript - Discord bot 没有获得所有用户
- c# - C# - BindingSource 删除当前
- java - 如何使用硒自动化单击警报上的是否按钮(而不是确定/取消)?
- hibernate - 我在执行此查询时收到错误“期望 IDENT,发现 '('”。
- postgresql - Postgres 内存不足错误
- android - 如何将嵌套的 Json 数组发布到服务器?
- sql-server - 如何在不同的服务器中加载数据
- swift - 如何在再次运行之前等待 Swift 的 URLSession 完成?
- typescript - 为什么 TypeScript 不抱怨带有计算键的 Partial 类型中的值不正确?
- vba - 在 vba 中传递表单信息