简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM