forked from apanesarr/playmyway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MongoCon.js
80 lines (63 loc) · 1.87 KB
/
MongoCon.js
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
78
79
'use strict';
var mongoose = require('mongoose');
var MongoCon = function(uri) {
this.uri = uri;
this.connected = false;
};
MongoCon.prototype.init = function() {
mongoose.connect(this.uri);
var mongocon = this;
var db = mongoose.connection;
db.on('error', function(err) {console.log('ERROR: ' + err);});
db.once('open', function callback() {
mongocon.connected = true;
console.log('Successfully connected to DB');
var songSchema = new mongoose.Schema({
votes: { type: Number, default: 0},
name: String,
path: String,
voters: Array,
lastPlayed: { type: Number, default: 0 }
});
mongocon.Song = mongoose.model('colx', songSchema, 'colx');
});
};
MongoCon.prototype.getSongs = function(cb) {
this.Song.find({}, {"name" : true, "lastPlayed" : true, "votes" : true}, {sort : {"votes" : -1, "lastPlayed" : 1}},function(err, res) {
if (err){
cb(err);
} else {
cb(null, res);
}
});
};
MongoCon.prototype.upvote = function(id, cb) {
this.Song.update({'_id': id}, { $inc: { votes: 1}}, {}, function(err){
if (err) throw err;
console.log("Upvoted", id);
cb();
});
};
MongoCon.prototype.playcur = function(cb) {
this.Song.findOneAndUpdate({}, {'lastPlayed': Date.now()}, {sort: {'votes': -1, 'lastPlayed' : 1}}, function(err, res) {
if (err){
cb(err);
} else {
console.log(res);
cb(null, res);
}
});
}
MongoCon.prototype.saveSong = function(path, name){
this.Song.findOneAndUpdate({'name': name, 'path': path, 'votes': 0, 'lastPlayed': 0}, {}, {upsert: true}, function(err){
if (err) throw err;
console.log("New song saved", name);
})
};
MongoCon.prototype.resetVotes = function(name){
this.Song.update({'path' : name}, {$set: {'votes': 0}}, function(err,res){
if (err) throw err;
console.log("Vote reset");
});
}
module.exports = MongoCon;