使用GridFS创建多个存储桶

时间:2019-03-19 01:52:07

标签: javascript mongodb gridfs multer-gridfs-storage

我正在Express和Node中使用GridFS库。我正在尝试创建多个存储桶。例如,我已经有一个名为头像的存储桶,用于存储图像。

    /* Start of mongo connection for uploading files */
const mongoURI = "mongodb://localhost:27017/PTAdata";
const conn = mongoose.createConnection(mongoURI);


let gfs;

conn.once('open', () => {
    gfs = stream(conn.db, mongoose.mongo);
    gfs.collection('avatars');
})

const storage = new GridFs({
    url: "mongodb://localhost:27017/PTAdata",
    file: (req, file) => {
    return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
        if (err) {
            return reject(err);
        }
        file.user = req.body.username
        const name = file.originalname
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
            filename: file.user,
            bucketName: 'avatars'
        };
        resolve(fileInfo);
        });
    });
    }
});
const upload = multer({ storage });

我现在要创建另一个称为音频的存储桶,该存储桶将存储mp3文件。我在https://docs.mongodb.com/manual/core/gridfs/上查看了GridFS的文档,它指出:“您可以选择其他存储桶名称,也可以在一个数据库中创建多个存储桶。”但是,它不提供任何见解或步骤。有没有人对GridFS库做过任何工作,并且知道如何创建多个存储桶?

1 个答案:

答案 0 :(得分:0)

您需要将另一个“新GridFS”对象存储在不同的变量中,而不是将其作为不同的存储属性传递给multer。在您的情况下,这应该可行:

const storage = new GridFs({
    url: "mongodb://localhost:27017/PTAdata",
    file: (req, file) => {
    return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
        if (err) {
            return reject(err);
        }
        file.user = req.body.username
        const name = file.originalname
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
            filename: file.user,
            bucketName: 'avatars'
        };
        resolve(fileInfo);
        });
    });
    }
});

const anotherStorage = new GridFs({
    url: "mongodb://localhost:27017/PTAdata",
    file: (req, file) => {
    return new Promise((resolve, reject) => {
        crypto.randomBytes(16, (err, buf) => {
        if (err) {
            return reject(err);
        }
        file.user = req.body.username
        const name = file.originalname
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
            filename: file.user,
            bucketName: 'mp3files'
        };
        resolve(fileInfo);
        });
    });
    }
});

const upload = multer({ storage });

const uploadSongs = multer({ storage: anotherStorage });

最后,您应该根据自己的端点在这些存储桶之间进行选择,例如:

app.post('/api/uploadAvatar', upload.any(), (req, res)=> {
... do stuff
}

app.post('/api/uploadMp3', uploadSongs.any(), (req, res)=> {
... do stuff
}

对我来说,在每种情况下(在file:(req,file)函数内部)更改gfs.collection()都是有意义的,但它也无需更改也可以工作。请注意,any()只是一个选择,它不是最安全的选择,但是对于测试代码非常有用。