nurl/models/url.js

33 lines
797 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({
2016-02-07 21:16:07 +00:00
_id: {type: String, required: true},
2017-08-05 20:14:17 +00:00
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({
_id: {type: Number, index: true},
long_url: String,
created_at: Date,
visits: {type: Number, default: 0}
2016-02-07 21:16:07 +00:00
});
urlSchema.pre('save', function(next){
2017-08-05 20:14:17 +00:00
const doc = this;
counter.findByIdAndUpdate({_id: 'url_count'}, {$inc: {seq: 1} }, function(error, counter) {
2016-02-07 21:16:07 +00:00
if (error)
return next(error);
doc.created_at = new Date();
doc._id = counter.seq;
next();
});
});
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;