【问题标题】:GridFSBucket ErrorsGridFSBucket 错误
【发布时间】:2020-08-17 14:24:49
【问题描述】:

当我尝试使用mongodb 中的GridFSBucket 时,会在fs.chunks 集合中创建块,但不会创建fs.files 文档。是否有可能发生这种情况的原因或者这是一个错误?

这将适用于我的本地机器和本地机器上的 docker,但不适用于 AWS EC2 上的 docker。

const { MongoClient, GridFSBucket } = require('mongodb');
const crypto = require('crypto');
const dotenv = require('dotenv');

dotenv.config();

const url = process.env.MONGO_URI;
const dbName = 'tree_club';
const opts = { useUnifiedTopology: true };

const getPosts = async () => {
    const client = await MongoClient.connect(url, opts);
    const db = client.db(dbName);
    const posts = await db.collection('post').find({}).sort({ created: -1 }).toArray();

    client.close();

    return posts;
};

const createPost = async (parent, { markdown, file }) => {
    const client = await MongoClient.connect(url, opts);
    const db = client.db(dbName);
    const bucket = new GridFSBucket(db);

    const fileId = file ? crypto.randomBytes(64).toString('hex') : undefined;
    const { ops: [post] } = await db.collection('post').insertOne({
        markdown,
        fileId,
        created: Date.now()
    });

    if (file) {
        await new Promise(async (resolve, reject) => {
            const { createReadStream } = await file;
            const readStream = createReadStream();
            const writeStream = bucket.openUploadStreamWithId(fileId, fileId);
            readStream.pipe(writeStream);
            readStream.on('error', () => {
                console.log('error');
            });
            readStream.on('finish', () => {
                resolve();
                client.close();
            });
        });
    } else {
        client.close();
    }

    return post;
};

const pipeImage = async (req, res) => {
    const client = await MongoClient.connect(url, opts);
    const db = client.db(dbName);
    const bucket = new GridFSBucket(db);

    try {
        const readStream = bucket.openDownloadStream(req.params.fileId);
        readStream.pipe(res);
        readStream.on('finish', () => {
            client.close();
        });
    } catch (err) {
        res.status(400).json('Image was not found');
    }
};

module.exports = { getPosts, createPost, pipeImage };

【问题讨论】:

    标签: node.js mongodb docker gridfs


    【解决方案1】:

    我搜索了这个问题的答案,结果发现 Node.js 版本 13 中存在流错误。

    我将我的 Node.js 版本降级为 12,上面的代码运行良好。

    【讨论】:

    • 也为我工作,我在版本 17 上,奇怪的是这个问题仍然存在于 node.js 中。感谢您发布您的解决方案,帮助了我。
    猜你喜欢
    • 2019-04-29
    • 2020-04-30
    • 1970-01-01
    • 2023-02-17
    • 2019-05-05
    • 2021-11-16
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    相关资源
    最近更新 更多