aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/app/models/Project.js
blob: 5f8e19695c2687b975f31e1cacdb39e1feb23c53 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

/**
 * Module dependencies
 */

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var ProjectSchema = new Schema({
    user:           { type: Schema.ObjectId, ref: 'User' }
  , name:           { type: String, default: '', trim: true }
  , description:    { type: String, default: '', trim: true }
  , currency:       { type: String, default: 'kr', trim: true }
  , public:         { type: String, default: 'invite-only' }
  , created:        { type: Date, default: Date.now }
  , updated:        { type: Date, default: Date.now }
  , shortURL:       { type: String, unique: true }
});

// the four validations below only apply if you are signing up traditionally

ProjectSchema.path('name').validate(function(name) {
    // if you're authenticated by any of the oauth strategies (facebook, twitter), don't validate
    return name.length;
}, 'Project name cannot be blank');



// This is a pre-save-hook. It runs every time an object is saved.
ProjectSchema.pre('save', function(next) {
    if (this.shortURL !== undefined) return next();
    var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    this.shortURL = '';
    for (var i = 0; i < 6; i++) {
        var x = Math.floor(Math.random() * chars.length);
        this.shortURL += chars.charAt(x);
    }
    console.log('SHORT: ' + this.shortURL);
    next();
});



ProjectSchema.statics = {

   /**
    * Find project by id
    *
    * @param {ObjectId} id
    * @param {Function} callback
    * @api private
    */

    load: function(id, callback) {
        this.findOne({ _id: id })
          .populate('user')
          .exec(callback);
    },


   /**
    * Find project my shortURL
    *
    * @param {shortURL} shortURL
    * @param {Function} callback
    * @api private
    */

    loadShort : function(shortURL, callback) {
        this.findOne({ shortURL: shortURL })
          .populate('user')
          .exec(callback);
    }

}

mongoose.model('Project', ProjectSchema);