Created
January 3, 2013 23:50
-
-
Save switzer/4448624 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Post = function(db) { | |
this.db = db; | |
}; | |
Post.prototype.get = function(req, res) { | |
var id = req.params.id; | |
var org = req.params.org; | |
var db = this.db; | |
console.log('Retrieving post: ' + id + ' from org: ' + org); | |
db.collection('ads', function(err, collection) { | |
collection.findOne({'_id':new BSON.ObjectID(id), 'org':org}, function(err, item) { | |
res.send(item); | |
}); | |
}); | |
}; | |
Post.prototype.find = function(req, res) { | |
var org = req.params.org; | |
var db = this.db; | |
console.log('Finding posts for org: ' + org); | |
db.collection('posts', function(err, collection) { | |
collection.find({'org':org}).toArray(function(err, items) { | |
res.send(items); | |
}); | |
}); | |
}; | |
Post.prototype.add = function(req, res) { | |
var org = req.params.org; | |
var post = req.body; | |
var db = this.db; | |
console.log('Adding post: ' + JSON.stringify(post) + ' for org: ' + org); | |
db.collection('posts', function(err, collection) { | |
collection.insert(post, {safe:true}, function(err, result) { | |
if (err) { | |
res.send({'error':'An error has occurred'}); | |
} else { | |
console.log('Success: ' + JSON.stringify(result[0])); | |
res.send(result[0]); | |
} | |
}); | |
}); | |
}; | |
Post.prototype.update = function(req, res) { | |
var id = req.params.id; | |
var org = req.params.org; | |
var post = req.body; | |
var db = this.db; | |
delete post._id; | |
console.log('Updating post: ' + id + ', org: ' + org); | |
console.log(JSON.stringify(post)); | |
db.collection('posts', function(err, collection) { | |
collection.update({'_id':new BSON.ObjectID(id)}, post, {safe:true}, function(err, result) { | |
if (err) { | |
console.log('Error updating post: ' + err); | |
res.send({'error':'An error has occurred'}); | |
} else { | |
console.log('' + result + ' document(s) updated'); | |
res.send(post); | |
} | |
}); | |
}); | |
}; | |
Post.prototype.remove = function(req, res) { | |
var id = req.params.id; | |
var org = req.params.org; | |
var db = this.db; | |
console.log('Deleting post: ' + id + ', org: ' + org); | |
db.collection('posts', function(err, collection) { | |
collection.remove({'_id':new BSON.ObjectID(id), 'org':org}, {safe:true}, function(err, result) { | |
if (err) { | |
res.send({'error':'An error has occurred - ' + err}); | |
} else { | |
console.log('' + result + ' document(s) deleted'); | |
res.send(req.body); | |
} | |
}); | |
}); | |
}; | |
module.exports = Post; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment