How to override a gridfs file within the Play Framework using reactivemongo?

524 Views Asked by At

I have the following code to write a gridfs file:

  request.body.files.toList.lastOption match {
    case Some(picture) => {
      val filename = picture.filename
      val contentType = picture.contentType
      picture.ref.moveTo(new File("/tmp/" + filename), true)

      val gridFS = new GridFS(db, "attachments")
      val fileToSave = DefaultFileToSave(filename, contentType)

      val futureResult: Future[ReadFile[BSONValue]] = gridFS.writeFromInputStream(fileToSave, new FileInputStream(new File("/tmp/" + filename)))
      ...

The code works fine but it duplicates the files in the collection when I write two files with the same name. I thought to create a unique index using the filename field but that would keep the first file and I need to keep the newest version. How can I do it?

Thanks,

GA

1

There are 1 best solutions below

0
Schleichardt On
  1. drop the index for the filename
  2. upload the new file, it is fine if multiple file versions have the same name
  3. rewrite the query something like that: find({filename: "some-file-name.txt"}).sort({uploadDate: -1}).limit(1), as a result you get only the most recent
  4. you can use the timestamp from the new uploaded file to delete all files with the same name and a smaller timestamp