Skip to content
forked from nswbmw/koa-mongo

MongoDB middleware for koa, support connection pool.

Notifications You must be signed in to change notification settings

mzmmlds/koa-mongo

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

52 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

koa-mongo

koa-mongo is a mongodb middleware for koa@2, support connection pool.

Install

npm i koa-mongo --save

Usage

app.use(mongo({
  host: 'localhost',
  port: 27017,
  user: 'admin',
  pass: '123456',
  db: 'test',
  authSource: 'admin',
  max: 100,
  min: 1,
  ...
}));

or

app.use(mongo({
  uri: 'mongodb://admin:123456@localhost:27017/test?authSource=admin', //or url
  max: 100,
  min: 1
  ...
}));

or

app.use(mongo({
  uri: 'mongodb://admin:123456@localhost:27017/test?authSource=admin', //or url
  max: 100,
  min: 1
  ...
}, {
  useUnifiedTopology: true
  ...
}
));

defaultOptions:

{
  host: 'localhost',
  port: 27017,
  db: 'test',
  authSource: 'admin',
  max: 100,
  min: 1,
  acquireTimeoutMillis: 100
}

More options see generic-pool.

ctx.mongo & ctx.db

ctx.mongo is an instance of MongoClient.

ctx.db === ctx.mongo.db(dbName)

Example

const Koa = require('koa')
const mongo = require('koa-mongo')

const app = new Koa()

app.use(mongo())
app.use(async (ctx, next) => {
  // ctx.db === ctx.mongo.db('test')
  const result = await ctx.db.collection('users').insert({ name: 'haha' })
  const userId = result.ops[0]._id.toString()
  ctx.body = await ctx.db.collection('users').find().toArray()
  ctx.db.collection('users').remove({
    _id: mongo.ObjectId(userId)
  })
})
app.listen(3000, () => {
  console.log('listening on port 3000')
})

Mongolass is a elegant MongoDB driver for Node.js.

License

MIT

About

MongoDB middleware for koa, support connection pool.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%