Skip to content

Instantly share code, notes, and snippets.

@Raynos
Last active December 10, 2015 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raynos/4464542 to your computer and use it in GitHub Desktop.
Save Raynos/4464542 to your computer and use it in GitHub Desktop.
A new mongo client API idea.
// MongoClient
// better name to come
var mongo = require("magic-mongo")
var fold = require("reducers/fold")
// Your user instance representation
var User = require("./user")
// create a mongo client connection
// valid options from MongoClient.connect
// http://mongodb.github.com/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect-options
// mongo is a thin wrapper around MongoClient and returns a client
var client = mongo("mongodb://localhost:27017/db_name"/*, options*/)
// Create a collection. With encoding / decoding logic in one place
// encode runs before insert to sanitize anything off your user instance
// decode runs before results of find / findOne / etc to convert to user instance
// client(colName, encodings) is a wrapper around db.collection
var collection = client("collectionName", {
encode: function (userInstance) {
;delete user._id
return user
}
, decode: function (raw) {
raw._id = String(raw._id)
return User(raw)
}
})
// collection itself is a wrapper around mongodb's Collection
// http://mongodb.github.com/node-mongodb-native/api-generated/collection.html
// Except everything goes through the encoding and return values are
// reducibles (https://github.com/gozala/reducers)
// fetch a user
var user = collection.findOne({
name: "James Bob"
})
fold(user, function (userInstance) {
// do stuff
})
// fetch all users
var users = collection.find()
fold(users, function (userInstances) {
// do stuff for each user instance
})
var user = User({ ... })
// insert a user
var result = collection.insert(user)
// update a user
var result = collection.update({
name: user.name
}, {
$set: {
name: "Some other name"
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment