var mongoose = require('mongoose');
const Counter = require('./Counter');

var NoticeSchema = new mongoose.Schema({
  date: {
    type: Date,
    default: Date.now
  },
  nid: {
    type: Number
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  title: {
    type: String,
    required: true
  },
  message: {
    type: String,
    required: true
  }
});


NoticeSchema.pre('save', function(next) {
  var notice = this;
  Counter.findByIdAndUpdate({
    _id: 'notices'
  }, {
    $inc: {
      seq: 1
    },
  }, {
    new: true,
    upsert: true
  }, function(error, counter) {
    if (error)
      return next(error);
    notice.nid = counter.seq;
    next();
  });
});


module.exports = mongoose.model('Notice', NoticeSchema);
