Search code examples
mongodbgridfsgridfs-stream

saving video/images to MongoDB in NodeJS server by using GridFS


I am looking for a sample example for storing videos/images in MongoDB using GridFS. I came across this official site and followed the below code snippet

var MongoClient = require('mongodb').MongoClient,
Grid = mongo.Grid;
// Connect to the db
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(err) return console.dir(err);
  var grid = new Grid(db, 'fs');
  var buffer = new Buffer("Hello world");
  grid.put(buffer, {metadata:{category:'text'}, content_type: 'text'}, function(err, fileInfo) {
    if(!err) {
      console.log("Finished writing file to Mongo");
    }
  });
});

When I run the code I am getting bellow error

Grid = mongo.Grid;
       ^
ReferenceError: mongo is not defined
at Object.<anonymous> (D:\Rahul\Nodejs\Fileupload\fileupload\Samples\grid-fs
\mongo.js:3:8)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3

please share any link for How to store files in MongoDB using GridFS in Nodejs.

EDIT 1

I tried a lot to get it work and finally I come to know the interface Grid is removed from Mongodb 2.1 so It won't work but there is no documentation for the replacement of Grid. Now I don't have clear idea about which one to use i.e GridStore, GridFSBucket, etc

Is this documentation misleading?


Solution

  • I believe what you want is:

    var mongo = require('mongodb');
    

    The things off the require('mongodb'}:

    var Db = require('mongodb').Db,
        MongoClient = require('mongodb').MongoClient,
        Server = require('mongodb').Server,
        ReplSetServers = require('mongodb').ReplSetServers,
        ObjectID = require('mongodb').ObjectID,
        Binary = require('mongodb').Binary,
        GridStore = require('mongodb').GridStore,
        Grid = require('mongodb').Grid,
        Code = require('mongodb').Code,
        BSON = require('mongodb').pure().BSON,
        assert = require('assert');
    

    From the documentation here.