0

When I am writing a file into GridFS using grid.put(), which has the same filename as a file stored before, the first file is going to be overwritten. Is it actually true that the same filename can only exist once in the database or am I doing something wrong?

My code looks like this:

var mongo = require('mongodb'),
  Server = mongo.Server,
  Db = mongo.Db,
  Grid = mongo.Grid;
  server = new Server('localhost', 27017, {auto_reconnect: true});
  db = new Db('mydb', server);

db.open(function(err, db) {
  var buffer = new Buffer("This is the first sample text");
  grid.put(buffer, {metadata:{}, filename: "test.txt", content_type: 'text'}, function(err, fileInfo) {
    buffer = new Buffer("This is the second sample text");
    // now this overwrites the first one...
    grid.put(buffer, {metadata:{}, filename: "test.txt", content_type: 'text'}, function(err, fileInfo) {
    });
  });
});

I thought that the file is specified unique by the ._id ObjectId and not by the filename. Am I wrong?

Thanks for your help!

heinob
  • 19,127
  • 5
  • 41
  • 61

2 Answers2

3

Per the GridFS spec the files are indexed by _id. The filename is part of the metadata, and does not have to be unique. If you put something with the same filename twice, you should be able to confirm both files exist by using mongofiles list from a command line.

What version of the MongoDB Node.js driver are you using? It looks like there was a driver bug corrected several months ago: Cannot save files with the same file name to GridFS.

Stennie
  • 63,885
  • 14
  • 149
  • 175
-2

Yes, they got overwritten, like on a real filesystem too! The _id is essential to the MongoDB internals (and for standart documents) but when you working with GridFS files the _id field does not matter, the file name need to be unique.

Also: What you would you expect to recieve when you do grid.get? The first file? The second? Both combined?

TheHippo
  • 61,720
  • 15
  • 75
  • 100
  • 1
    Your question assumes that the parameter for grid.get() is . But it is not! Due to the [documentation](http://mongodb.github.com/node-mongodb-native/api-generated/grid.html#get) it is . So I would expect to get exactly the document with this _id, despite the fact that there are other documents with the same name. – heinob Jun 20 '12 at 06:47