Created
October 2, 2010 09:29
-
-
Save drewlesueur/607493 to your computer and use it in GitHub Desktop.
Mongo db crud example
This file contains hidden or 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
#Examples of crud operations on node.js using node-mongodb-native (in coffeescript) | |
mongo = require("mongodb") | |
host = 'localhost' | |
port = mongo.Connection.DEFAULT_PORT | |
this.ObjectID = mongo.ObjectID | |
this.db = new mongo.Db 'mydb', new mongo.Server(host, port, {}), {} | |
this.methods = | |
create : (args, req, res) -> | |
db.collection args.type, (err, collection) -> | |
if err | |
res.send "bro" | |
else | |
collection.insert args.obj, (err, docs) -> | |
res.send docs | |
request : (args, req, res) -> | |
db.collection args.type, (err, collection) -> | |
if err | |
res.send "brokep" | |
else | |
if "_id" of args.wh | |
args.wh._id = ObjectID.createFromHexString(args.wh._id) | |
collection.find args.wh, (err, cursor) -> | |
cursor.toArray (err, docs) -> | |
res.send docs | |
update : (args, req, res) -> | |
db.collection args.type, (err, collection) -> | |
if err | |
res.send "broke" | |
else | |
if "_id" of args.wh | |
args.wh._id = ObjectID.createFromHexString(args.wh._id) | |
collection.update args.wh, args.va, {upsert: args.upsert, multi: args.multi}, (err, wha) -> | |
res.send wha | |
delete: (args, req, res) -> | |
db.collection args.type, (err, collection) -> | |
if err | |
res.send "broke" | |
else | |
if "_id" of args.wh | |
args.wh._id = ObjectID.createFromHexString(args.wh._id) | |
collection.remove args.wh, (err, collection) -> | |
res.send "done" | |
this.db.open () -> | |
app.post "/methods/:method/:args", (req, res) -> | |
args = req.param("args") | |
args = decodeURIComponent(args); | |
methods[req.param("method")] JSON.parse(args), req, res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment