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!
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.
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?