var mongoose = require('mongoose'); var uniqueValidator = require('mongoose-unique-validator'); var slug = require('slug'); var User = mongoose.model('User'); var ProductSchema = new mongoose.Schema({ ordering: Number, title: String, slug: { type: String, lowercase: true, unique: true }, prime_achat: Number, prime_vente: Number, metal: { type: mongoose.Schema.Types.ObjectId, ref: 'Metal' }, poids: Number, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, favoritesCount: { type: Number, default: 0 } }, {timestamps: true, toJSON: {virtuals: true}}); ProductSchema.plugin(uniqueValidator, { message: 'is already taken' }); ProductSchema.pre('validate', function (next) { if (!this.slug) { this.slugify(); } next(); }); ProductSchema.methods.slugify = function () { this.slug = slug(this.title) + '-' + (Math.random() * Math.pow(36, 6) | 0).toString(36); }; ProductSchema.methods.updateFavoriteCount = function () { var product = this; return User.count({ favorites: { $in: [product._id] } }).then(function (count) { product.favoritesCount = count; return product.save(); }); }; ProductSchema.methods.toJSONFor = function(user){ return { ordering: this.ordering, title: this.title, slug: this.slug, prime_achat: this.prime_achat, prime_vente: this.prime_vente, metal: this.metal.toJSONFor(), poids: this.poids, createdAt: this.createdAt, updatedAt: this.updatedAt, favorited: user ? user.isFavorite(this._id) : false, favoritesCount: this.favoritesCount, author: this.author.toProfileJSONFor(user) }; }; mongoose.model('Product', ProductSchema);