nurl/models/url.js

33 lines
783 B
JavaScript
Raw Normal View History

2017-08-05 20:14:17 +00:00
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
2016-02-07 21:16:07 +00:00
2017-08-05 20:14:17 +00:00
const CounterSchema = Schema({
2017-09-05 14:53:07 +00:00
_id: { type: String, required: true },
seq: { type: Number, default: 1000 }
2016-02-07 21:16:07 +00:00
});
2017-08-05 20:14:17 +00:00
const counter = mongoose.model('counter', CounterSchema);
2016-02-07 21:16:07 +00:00
// create a schema for our links
2017-08-05 20:14:17 +00:00
const urlSchema = new Schema({
2017-09-05 14:53:07 +00:00
_id: { type: Number, index: true },
long_url: String,
created_at: Date,
visits: { type: Number, default: 0 }
2016-02-07 21:16:07 +00:00
});
2017-09-05 14:53:07 +00:00
urlSchema.pre('save', function(next) {
const doc = this;
counter.findByIdAndUpdate({ _id: 'url_count' }, { $inc: { seq: 1 } }, function(error, counter) {
if (error)
return next(error);
doc.created_at = new Date();
doc._id = counter.seq;
next();
2016-02-07 21:16:07 +00:00
});
});
2017-08-05 20:14:17 +00:00
const Url = mongoose.model('Url', urlSchema);
2016-02-07 21:16:07 +00:00
module.exports = Url;