aheckmann / gridfs-stream

Easily stream files to and from MongoDB
MIT License
615 stars 120 forks source link

Document unavailable when 'end' fires #3

Closed nrw closed 12 years ago

nrw commented 12 years ago

This is probably the issue affecting gridform that i posted here. Same symptoms and it looks like gridform uses gridfs-stream in the same manner.

// requires omitted

read_id = // id string for a file i'm able to access in the mongo shell
write_id = new ObjectID();

// Is there a way to do this with gridstream.createReadStream?
// I don't see a way to open a file by id.
readStore = new GridStore(db, read_id, 'r');

readStore.open(function(err, readFile) {
  // make streams
  var readStream = readFile.stream();
  var writeStream = gridstream.createWriteStream(write_id);

  // pipe
  readStream.pipe(writeStream);
  readStream.on('end', function() {

    // version 1: this one works
    setTimeout(function() {
      db.collection('fs.files', function(err, coll) {
        coll.findOne({
          _id: write_id
        }, function(err, doc) {
          // doc exists
        });
      });
    }, 30);

    // version 2: this one doesn't work
    db.collection('fs.files', function(err, coll) {
      coll.findOne({
        _id: write_id
      }, function(err, doc) {
        // doc is null
      });
    });

  });
});
aheckmann commented 12 years ago

listen to the writestream close event instead of readstream as the end of the read doesn't mean the file has finished writing yet.