npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mongoose-crate

v1.1.0

Published

Attach files to MongoDB models via Mongoose.js

Downloads

49

Readme

mongoose-crate

Dependency Status devDependency Status Build Status Coverage Status

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 = require('mongoose')
const crate = require('mongoose-crate')
const LocalFS = require('mongoose-crate-localfs')

const PostSchema = new mongoose.Schema({
  title: String
})

PostSchema.plugin(crate, {
  storage: new LocalFS({
    directory: '/path/to/storage/directory'
  }),
  fields: {
    attachment: {}
  }
})

const Post = mongoose.model('Post', PostSchema)

.. then later:

const post = new Post()
post.attach('attachment', {path: '/path/to/file'}, (error) => {
	// attachment is now attached and post.attachment is populated e.g.:
	// post.attachment.url

	// don't forget to save it..
	post.save((error) => {
		// post is now persisted
	})
})

.. or using promises:

const post = new Post()
post
  .attach('attachment', {path: '/path/to/file'})
  .then(() => post.save())

Arrays

Files can be stored in arrays as well as individual properties. Just specify the array property to the field definition:

const mongoose = require('mongoose')
const crate = require('mongoose-crate')
const LocalFS = require('mongoose-crate-localfs')

const PostSchema = new mongoose.Schema({
  title: String
})

PostSchema.plugin(crate, {
  storage: new LocalFS({
    directory: '/path/to/storage/directory'
  }),
  fields: {
    attachments: {
      array: true
    }
  }
})

const Post = mongoose.model('Post', PostSchema)

.. then later:

const post = new Post()
post.attach('attachments', {path: '/path/to/file'}, (error) => {
  // post.attachments.length == 1

  post.attach('attachments', {path: '/path/to/another/file'}, (error) => {
    // post.attachments.length == 2
  })
})

.. or using promises:

const post = new Post()
post.attach('attachments', {path: '/path/to/file'})
  .then(() => post.attach('attachments', {path: '/path/to/another/file'}))

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.post('/upload', (req, res, next) => {
  const post = new mongoose.model('Post')()
  post.title = req.body.title
  post.description = req.body.description
  post.attach('image', req.files.image)
    .then(() => post.save())
    .then(() => res.send('Post has been saved with file!'))
    .catch(err => next(err))
})

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.remove({...}, callback)

or this:

MySchema.findOne({...}, (err, doc) => {
  doc.remove(callback)
})

..but not this:

MySchema.findOne({...}).remove(callback)

Array attachment deletion

const mongoose = require('mongoose')
const crate = require('mongoose-crate')
const LocalFS = require('mongoose-crate-localfs')

const MySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
})

MySchema.plugin(crate, {
  storage: new LocalFS({
    directory: '/path/to/storage/directory'
  }),
  fields: {
    files: {
      array: true
    }
  }
})

// ...

const model = new MySchema()
model.name = 'hello'
model.attach('files', {
    path: file
}, callback)

// some time later remove one of the array entries

model.files.pop()
model.save()

Non array attachment deletion

const mongoose = require('mongoose')
const crate = require('mongoose-crate')
const LocalFS = require('mongoose-crate-localfs')

const MySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  }
})

MySchema.plugin(crate, {
  storage: new LocalFS({
    directory: '/path/to/storage/directory'
  }),
  fields: {
    file: {}
  }
})

// ...

const model = new MySchema()
model.name = 'hello'
model.attach('file', {
    path: file
}, callback)

// some time later delete the file

model.file = null
model.save()