gridfs-extra
v1.0.2
Published
A simple wrapper for the MongoDB GridFSBucket-API
Downloads
2
Readme
gridfs-extra
A simple wrapper for the MongoDB GridFSBucket-API. If you need a similar wrapper for mongoose GridFSBucket-API, see mongoose-gridfs-extra
This package is designed to avoid operations on the stream objects provided by the native API, thereby saving time.
Install
install npm package
npm install gridfs-extra
or clone from Github
# ssh
git clone [email protected]:peachest/gridfs-extra.git
# http
git clone https://github.com/peachest/gridfs-extra.git
Usage
Complete runnable example is provided. See example/example.{cjs,mjs}
.
After cloning the repository to local, run:
cd gridfs-extra
node example/example.cjs
node example/example.mjs
Import
// ESModule
import * as gridfs from "gridfs-extra"
import mongodb from "mongodb"
// or CommandJS
const mongodb = require('mongodb')
const gridfs = require("gridfs-extra")
Connect to Mongodb Server
const client = new mongodb.MongoClient("mongodb://localhost:27017");
await client.connect()
// or top-level await is not allowed
client.connect().then(async () => {
// put the following code here
})
Create GridFS bucket
const db = client.db('test')
const bucketName = "testBucket";
const options = {
bucketName
}
// gridfs-extra
const bucket = gridfs.createGridFSBucket(db, options)
// or mongodb native API
const bucket = new mongodb.GridFSBucket(db, options) ;
Write file into bucket
// Read Buffer type file content
const fileName = ""
let file = await fs.readFile("")
// Write file into bucket
const gridFSFile = await gridfs.writeFileByName(bucket, file, fileName)
const id = gridFSFile._id
Read file from bucket
// Read file from bucket
file = await gridfs.readFileById(bucket, id)
// or use fileName
file = await gridfs.readFileByName(bucket, fileName, {
revision: -1 // default value
})
:warning: A bucket can store files with the same name. If you wonder how the bucket will retrun when read file by name, see the following native doc from mongodb gridfs bucket:
If there are multiple files with the same name, this will stream the most recent file with the given name (as determined by the uploadDate field). You can set the revision option to change this behavior.
As for the revision:
The revision number relative to the oldest file with the given filename.
- 0 gets you the oldest file,
- 1 gets you the 2nd oldest,
- -1 gets you the newest.
License
Apache 2.0