Attachments: Storing Attachments
In order to store an attachment in RavenDB you need to create a document. Then you can attach an attachment to the document using the session.advanced.attachments.store()
method.
Attachments, just like documents, are a part of the session and will be only saved on the Server when DocumentSession.saveChanges()
is executed (you can read more about saving changes in session here).
Syntax
Attachments can be stored using one of the following session.advanced.attachments.store()
methods:
session.advanced.attachments.store(documentId, name, stream, [contentType]);
session.advanced.attachments.store(entity, name, stream, [contentType]);
Parameters | ||
---|---|---|
entity or documentId | object or string | instance of the entity or the entity ID |
name | string | attachment name |
stream | Readable or Buffer |
attachment content |
contentType | string | attachment content type |
Example
const session = store.openSession();
const file1 = fs.createReadStream("001.jpg");
const file2 = fs.createReadStream("002.jpg");
const file3 = fs.createReadStream("003.jpg");
const file4 = fs.createReadStream("004.mp4");
const album = new Album();
album.name = "Holidays";
album.description = "Holidays travel pictures of the all family";
album.tags = [ "Holidays Travel", "All Family" ];
await session.store(album, "albums/1");
session.advanced.attachments
.store("albums/1", "001.jpg", file1, "image/jpeg");
session.advanced.attachments
.store("albums/1", "002.jpg", file2, "image/jpeg");
session.advanced.attachments
.store("albums/1", "003.jpg", file3, "image/jpeg");
session.advanced.attachments
.store("albums/1", "004.mp4", file4, "video/mp4");
await session.saveChanges();