mongoose-crate
mongoose-crate is a plugin for Mongoose for attaching files to documents.
File meta data is stored in MongoDB, whereas the actual file itself is stored on the local filesystem, Amazon S3 or Google Cloud Storage. For others pull requests are gratefully accepted.
Uploaded images can optionally be passed through ImageMagick to generate one or more images (e.g. thumbnails, full size, original image, etc) before saving.
The architecture is nominally based on mongoose-attachments but that project hasn't seen updates in a while.
Usage
The following example extends the 'Post' model to use attachments with a property called 'attachment'.
const mongoose = const crate = const LocalFS = const PostSchema = title: String PostSchema const Post = mongoose
.. then later:
const post = post
.. or using promises:
const post = post
Arrays
Files can be stored in arrays as well as individual properties. Just specify the array
property to the field definition:
const mongoose = const crate = const LocalFS = const PostSchema = title: String PostSchema const Post = mongoose
.. then later:
const post = post
.. or using promises:
const post = post
Images
See mongoose-crate-gm.
mongoose-crate-imagemagick is also available but should be considered deprecated because the underlying dependencies are no longer maintained.
Using with Express.js uploads
Assuming that the HTML form sent a file in a field called 'image':
app
Metadata
Basic meta data is captured about uploaded files.
Example:
"name" : "dragon.png" "size" : 26887 "type": "image/png" "url" : "http://my_bucket.s3.amazonaws.com/folder/4fbaaa31db8cec0923000019-medium.png"
Plugins can add extra meta data. E.g. mongoose-crate-imagemagick adds width, height, etc.
Deletes and updates
If you delete a model, any attached files will be removed along with it (with one caveat, see Schema methods vs Queries below). Similarly, if you attach a file to a field that already has an attachment, the old file will be deleted before the new one is added.
For attachment arrays, when the model is saved, any attachments that are no longer in the array will have their files removed.
Schema methods vs Queries
Removal of files happens via middleware - if you use findById
, findOne
or anything else that returns a Query and call methods on that query, middleware is not executed. See the Mongoose middleware docs for more.
In short, do this sort of thing:
MySchema
or this:
MySchema
..but not this:
MySchema
Array attachment deletion
const mongoose = const crate = const LocalFS = const MySchema = name: type: String required: true MySchema // ... const model = modelname = 'hello'model // some time later remove one of the array entries modelfilesmodel
Non array attachment deletion
const mongoose = const crate = const LocalFS = const MySchema = name: type: String required: true MySchema // ... const model = modelname = 'hello'model // some time later delete the file modelfile = nullmodel