Reputation: 4509
I am developing an application when some user can add a comentary and attach a file, it's a simple form in the UI. In this case some time is optional add a file but it's obligatory add a comentary. In the case when the user add a file in the comentary... i have this code:
BasicDBObject metadata = new BasicDBObject();
metadata.put("_id", UUID.randomUUID().toString());
metadata.put("comentary", "Hola que hace");
metadata.put("date", (new Date().toString()));
metadata.put("applicationID", "1111-111");
GridFS gridFS = new GridFS(mongoTemplate.getDb(), "noteAndFile");
GridFSInputFile gfsFile = gridFS.createFile(file);
gfsFile.put("metadata", metadata);
gfsFile.save();
this code works, but then the user doesn't add a file I have this:
BasicDBObject metadata = new BasicDBObject();
metadata.put("_id", UUID.randomUUID().toString());
metadata.put("comentary", "Segundo persist");
metadata.put("date", (new Date().toString()));
metadata.put("applicationID", "2222-222");
GridFS gridFS = new GridFS(mongoTemplate.getDb(), "noteAndFile");
GridFSInputFile gfsFile = gridFS.createFile();
gfsFile.put("metadata", metadata);
gfsFile.save();
but gfsFile.save();
return nul. I definitely need to use this way to later obtain a list of comments that have or do not have file attachment.
BasicDBObject allComentaryWithOrNotFileAttach = new BasicDBObject();
List<GridFSDBFile> files = gridFS.find(allComentaryWithOrNotFileAttach);
how can I do it?
Upvotes: 2
Views: 1238
Reputation: 50416
I think the only thing you are missing here is an "empty" input stream where there is no file attachment. This is fairly easy to fix:
String mystring = new String(); // an empty string
GridFS gridFS = new GridFS(mongoTemplate.getDB(),"noteAndFile");
GridFSInputFile gfsFile = gridFS.createFile(
new ByteArrayInputStream( mystring.getBytes() )
);
BasicDBObject meta = new BasicDBObject();
meta.put("comments","hi");
gfsFile.put("metadata",meta);
gfsFile.save();
System.out.println(gfsFile.getId()); // gives me the _id of the object saved
And when I go and look for that in the shell:
> db.noteAndFile.files.findOne()
{
"_id" : ObjectId("55a909057c712d9f488c88e7"),
"chunkSize" : NumberLong(261120),
"length" : NumberLong(0),
"md5" : "d41d8cd98f00b204e9800998ecf8427e",
"filename" : null,
"contentType" : null,
"uploadDate" : ISODate("2015-07-17T13:54:13.837Z"),
"aliases" : null,
"metadata" : {
"comments" : "hi"
}
}
Of course since the "bytestream" here is empty, then the "chunks" collection has no objects associated. But that should be expected.
So you can always grab this object later and add real content to it, if and when this becomes available.
Upvotes: 2