Alexander
Alexander

Reputation: 1378

how to replace gridStore to gridFSBucket?

I have this error message:

(node:11976) DeprecationWarning: GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead

and sometimes I have trouble viewing the picture , I guess because of that, due to poor documentation I have no idea how to switch my code to GridFSBucket, this is it:

conn.once("open", () => {
  // Init stream
  gfs = Grid(conn.db, mongoose.mongo);
  //gfs = new mongoose.mongo.GridFSBucket(conn.db);
  gfs.collection("user_images");
});


var storageImage = new GridFsStorage({
  url: dbURI,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString("hex") + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: "user_images"
        };
        resolve(fileInfo);
      });
    });
  }
});
const uploadImage = multer({ storage: storageImage });

    const uploadImage = multer({ storage: storageImage });
router.get("/image/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }

    if (file.contentType === "image/jpeg" || file.contentType === "image/png") {
      const readstream = gfs.createReadStream(file.filename);
      //const readstream = gridFSBucket.openUploadStream(file.filename);
      readstream.pipe(res);
    } else {
      res.status(404).json({
        err: "Not an image"
      });
    }
  });
});

I would really appreciate the help, what do I need to change here to make it work with GridFsBucket, huge thanks in advance!

Upvotes: 12

Views: 4725

Answers (3)

General Butt Naked
General Butt Naked

Reputation: 31

I ended up having the same issue, you have most likely determined that readstream = gfs.createReadStream(file.filename); is what is causing the error. Just need to add a new variable and change one line.

//add var
let gridFSBucket;
let gfs;
connection.once('open', () => {
  gfs = Grid(conn.db, mongoose.mongo);
  // add value to new var
  gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db, {
    bucketName: 'user_images'
  });

  gfs = Grid(connection.db, mongoose.mongo);
  gfs.collection(image_bucket_name);

  if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
    //now instead of const readstream = gfs.createReadStream(file.filename);
    //add this line
    const readStream = gridFSBucket.openDownloadStream(file._id);
    readSteam.pipe(res);
  }
});

If you run into ( DeprecationWarning: GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead ), hope this saves you some time.

Upvotes: 2

Nikitas IO
Nikitas IO

Reputation: 1181

Way late to the party, but since I've stumbled upon the same problem and the existing answer doesn't solve the problem, I'll go ahead and post what I found in case somebody else stumbles upon the same problem in the future:

// Old Way:
const conn = mongoose.createConnection(youConnectionURI);
const gfs = require('gridfs-store')(conn.db);
gfs.collection('yourBucketName');

// New Way:
const conn = mongoose.createConnection(youConnectionURI);
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db, {bucketName: 'yourBucketName'});

For more info about how to perform CRUD operations using GridFSBucket check out this page and this page.

Upvotes: 2

Sheece Gardazi
Sheece Gardazi

Reputation: 567

I followed this tutorial to create this recipe. Tutorial is awesome it explains all the steps quite nicely. Complete code example can be found here.

Html form example:

<form action="http://localhost:4000/upload" method="post" enctype="multipart/form-data">
      <input type="file"  name='image' />
      <button type="submit" >Submit</button>
</form>

Controller recipe to upload image to mongodb:

const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');

const mongodbURL="mongodb+srv://<user>:<pass>@cluster.mongodb.net/<databaseName>"
const connection = mongoose.createConnection(mongoURI);

// Init gfs
let gfs;
const image_bucket_name = "user_images"

connection.once('open', () => {
    // Init stream
    gfs = Grid(connection.db, mongoose.mongo);
    gfs.collection(image_bucket_name);
})

// Create storage engine
const storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (error, buffer) => {
                if (error) {
                    return reject(error);
                }
                const filename = buffer.toString('hex') + path.extname(file.originalname);
                const fileinfo = {
                    filename: filename,
                    bucketName: image_bucket_name
                };
                resolve(fileinfo);
            })
        });
    }
});

const upload = multer({ storage });
app.post('/upload', upload.single('image'), async (req, res) => {
    console.log("uploaded image: "+req.file.
});

Upvotes: 0

Related Questions