首页 > 解决方案 > 如何使用nestJS将文件上传到mongoose上的mongodb?

问题描述

你好请问有人知道如何使用nestJS将文件上传到MongoDB(猫鼬)吗?

我已经能够@Post 将文件上传到我的nestJS projet 和@Get,但知道我想使用mongoose 发布到mongodb,请帮助

标签: mongodbfilemongoosenestjs

解决方案


我不建议将图像存储在您的数据库中,但您可以这样做:

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 并将链接保存在数据库中。


推荐阅读