panta / mongoose-file

Mongoose plugin adding a file field to a schema - useful for nodejs file uploads
MIT License
33 stars 2 forks source link

About mongoose-file

mongoose plugin that adds a file field to a mongoose schema. This is especially suited to handle file uploads with nodejs/expressjs.

Install

npm install mongoose-file

Usage

The plugin adds a file field to the mongoose schema. Assigning to the file property of the field causes (optionally) the file to be moved into place (see upload_to below) and the field sub-properties to be assigned. This field expects to be assigned (to its file sub-field, as said) an object with a semantic like that of an expressjs request file object (see req.files). Assigning to the field file property caused the instance to be marked as modified (but it's not saved automatically).

The field added to the schema is a compound JavaScript object, containing the following fields:

These values are extracted from the request-like file object received on assignment.

When attaching the plugin, it's possible to specify an options object containing the following parameters:

JavaScript

var mongoose = require('mongoose');
var filePluginLib = require('mongoose-file');
var filePlugin = filePluginLib.filePlugin;
var make_upload_to_model = filePluginLib.make_upload_to_model;

...

var uploads_base = path.join(__dirname, "uploads");
var uploads = path.join(uploads_base, "u");
...

var SampleSchema = new Schema({
  ...
});
SampleSchema.plugin(filePlugin, {
    name: "photo",
    upload_to: make_upload_to_model(uploads, 'photos'),
    relative_to: uploads_base
});
var SampleModel = db.model("SampleModel", SampleSchema);

CoffeeScript

mongoose = require 'mongoose'
filePluginLib = require 'mongoose-file'
filePlugin = filePluginLib.filePlugin
make_upload_to_model = filePluginLib.make_upload_to_model

...
uploads_base = path.join(__dirname, "uploads")
uploads = path.join(uploads_base, "u")
...

SampleSchema = new Schema
  ...
SampleSchema.plugin filePlugin,
    name: "photo"
    upload_to: make_upload_to_model(uploads, 'photos')
    relative_to: uploads_base
SampleModel = db.model("SampleModel", SampleSchema)

Bugs and pull requests

Please use the github repository to notify bugs and make pull requests.

License

This software is © 2012 Marco Pantaleoni, released under the MIT licence. Use it, fork it.

See the LICENSE file for details.