Skip to content

Instantly share code, notes, and snippets.

@akabab
Last active May 26, 2018 14:45
Show Gist options
  • Save akabab/602aae255a3570fe70c3dc137898ac6c to your computer and use it in GitHub Desktop.
Save akabab/602aae255a3570fe70c3dc137898ac6c to your computer and use it in GitHub Desktop.
Mongodb (w/ Monk) NodeJS + Proxy helper
const connect = require('monk')
const url = 'mongodb://localhost:27017/livecodings'
const handler = { get: (obj, prop) => obj[prop] || obj.get(prop) }
const db = new Proxy(connect(url), handler)
// db.users -> access 'users' collection instead of db.get('users')
const readUsers = async () => db.users.find({})
readUsers.byId = id => db.users.findOne({ _id: id })
readUsers.byEmail = email => db.users.findOne({ email })
@akabab
Copy link
Author

akabab commented May 26, 2018

/!\ 'close', 'create' & 'get' (existing methods on db object) should not be used as collection names

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment