The Grid
object acts as a representation of GridFS. It provides a simple interface to read and write binary data to GridFS. You can instantiate the Grid
object by calling the Grid()
constructor from an instance of the Db
object. For example, the following code connects to MongoDB and creates a Grid
object attached to the fs
collection:
MongoClient.connect("mongodb://localhost/", function(err, db) {
var grid= new Grid(db, 'fs'),
});
The Grid
object provides several methods that allow you to put data into the grid, retrieve data in the grid, and remove data from the grid. The data stored in the grid is stored in binary format, so it must be put into the grid and read from the grid as Buffer
objects. To put data into the grid, use the put()
method, like this:
put(data, [options], callback)
The put()
method writes data
, which is a Buffer
object to GridFS. The optional options
parameter is an object that specifies where and how to write the data. callback
should accept an error
object as the first parameter and a reference to the Grid
object as the second. You can set these options in options
:
_id: A unique ID for the file
root: The name of the root collection to use
content_type: The MIME type of the file
chunk_size: The size of each chunk of the file, in bytes
metadata: An object that allows you to add any additional metadata that you want
The get()
method allows you to read data back from the Grid
object. The get()
method uses the following syntax:
get(id, callback)
The id
parameter corresponds to the _id
setting in the options
parameter of put()
. The callback function should accept an error
object as the first parameter and a Buffer
object with retrieved data as the second.
To remove data from the grid, you can use the delete()
method:
delete(id, callback)
The id
parameter corresponds to the _id
setting in the options
parameter of put()
. The callback function should accept an error
object as the first parameter and reference to the Grid
object as the second.
To illustrate the use of the Grid
object, Listing 17.1 implements a Grid
object, writes a string to it, and then reads the string from it and deletes it. The string can be any binary data, such as an image file. Figure 17.5 shows the output of Listing 17.1.
01 var MongoClient = require('mongodb').MongoClient,
02 GridStore = require('mongodb').GridStore,
03 Grid= require('mongodb').Grid;
04 MongoClient.connect("mongodb://localhost/", function(err, db) {
05 var grid= new Grid(db, 'fs'),
06 var data = new Buffer('Hello world'),
07 console.log("
Original Data: ");
08 console.log(data.toString());
09 grid.put(data, {_id: "test.file"}, function(err, results) {
10 console.log("
Put Results: ");
11 console.log(results);
12 grid.get("test.file", function(err, data) {
13 console.log("
Before Delete Get: ");
14 console.log(data.toString());
15 grid.delete("test.file", function(err, results) {
16 console.log("
Delete Results: ");
17 console.log(results);
18 db.close();
19 });
20 });
21 });
22 });