mongoose-gridfs-extra
v1.0.1
Published
A simple wrapper for the Mongoose GridFSBucket-API
Downloads
4
Maintainers
Readme
mongoose-gridfs-extra
A simple wrapper for the Mongoose GridFSBucket-API. If you need a similar wrapper for Mongodb GridFSBucket-API, see 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 mongoose-gridfs-extra
or clone from Github
# ssh
git clone [email protected]:peachest/mongoose-gridfs-extra.git
# http
git clone https://github.com/peachest/mongoose-gridfs-extra.git
Usage
Complete runnable example is provided. See example/example.{cjs,mjs}
.
After cloning the repository to local, run:
cd mongoose-gridfs-extra
node example/example.cjs
node example/example.mjs
Import
// ESModule
import * as gridfs from "mongoose-gridfs-extra"
import mongoose from "mongoose"
// or CommandJS
const {mongoose} = require('mongoose')
const gridfs = require("mongoose-gridfs-extra")
Connect to Mongodb Server
const uri = 'mongodb://localhost:27017/test';
const connect = await mongoose.createConnection(uri).asPromise()
Create GridFS bucket
const db = connect.db
const bucketName = "testBucket";
const options = {
bucketName
}
// mongoose-gridfs-extra
const bucket = gridfs.createGridFSBucket(db, options)
// or mongodb native API
const bucket = new mongoosemongodb.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