【问题标题】:How to create an array of images and store it in mongodb如何创建图像数组并将其存储在mongodb中
【发布时间】:2019-12-03 19:14:48
【问题描述】:

我想制作一个帖子提要 nodejs 应用程序,用户将在其中上传最多 10 张带有简短描述的图片,就像 instagram 和 facebook 一样。我可以使用 express-fileupload npm 包存储图像,但如何创建图像数组并将其存储到 mongodb。

我做了一个类似这样的 PostSchema

var postSchema = new schema({
    username: {
        type: String
    },
    photos: {
        type: Array
    },
    videos: {
        type: Array
    },
    likes: {
        type: Array,
    },
    description: {
        type: String
    }
})

postfeed 控制器看起来像这样

router.post('/post', verifyToken, (req, res) => {
    var description = req.body.description
    var email = req.body.email

    if (req.files) {
        var file = req.files.photos;
        for (let i = 0; i < file.length; i++) {

            var path = appRoot + '/uploads/posts/' + req.user._id
            fs.mkdir(path, () => {})
            var postImages = path + '/' + file[i].md5 + '-' + Date.now() + '.png'
            file[i].mv(postImages)
        }
    }
})

【问题讨论】:

  • 只存储fs读取的结果

标签: node.js mongodb


【解决方案1】:

根据文件大小,您可以采取多种方法,尝试使用数据类型为“binData”将图像存储到 mongoDB。如果文件大小超过 16mb,那么您需要开始查看 GridFSenter link description here,因为您要存储图像数组,然后检查这些有用的链接: enter link description hereenter link description here

作为一个建议,如果您的项目有云基础设施,那么将图像文件存储在 AWS S3 或 Azure blob 中并将相应的链接作为数组存储在 mongoDB 集合中将非常容易(我们正在做什么以及更合适的实现这些天),使用该 UI 可以从直接从云访问的提供的链接呈现这些图像。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多