Code Monkey home page Code Monkey logo

koa-mongoose's Introduction

koa-mongoose

๐Ÿƒ Mongoose middleware for Koa 2

npm CI Status Coveralls Status Dependencies Dev Dependencies


Features

  • Adds model() and document() to the koa ctx
  • Config for automatically loading schemas and events on the mongoose instance

Basic Usage

The middleware config accepts a user and pass or you can use a uri or url as an escape hatch for other url schemes.

Unauthenticated connections will also work by omitting the user and pass and only providing a host, port and db.

Note: If you're using the mongodb+srv syntax to connect to MongoDB Atlas, you should use the mongoose dbName option to specify the database because you currently cannot in the connection string. (source) Be sure to change the default koa-mongoose db option to match as well.

const Koa = require('koa');
const mongoose = require('@south-paw/koa-mongoose');

const app = new Koa();

// middleware config
const config = {
  host: 'localhost',
  port: '27017',
  user: '',
  pass: '',
  db: 'test',
  mongoOptions: {
    // these are the default middleware options, see https://mongoosejs.com/docs/connections.html#options
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    reconnectTries: Number.MAX_SAFE_INTEGER, // Never stop trying to reconnect
    reconnectInterval: 500, // Reconnect every 500ms
    poolSize: 10, // Maintain up to 10 socket connections
    bufferMaxEntries: 0, // If not connected, return errors immediately rather than waiting for reconnect
    connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
    socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
  },
  schemas: {
    // schemas recieve the middleware's mongoose instance, see https://mongoosejs.com/docs/schematypes.html
    users: ({ Schema }) =>
      new Schema(
        {
          name: { type: String },
          pets: [Schema.Types.ObjectId],
        },
        { collection: 'users' },
      ),
    pets: ({ Schema }) =>
      new Schema(
        {
          type: { type: String },
          name: { type: String },
        },
        { collection: 'pets' },
      ),
  },
  events: {
    // see https://mongoosejs.com/docs/api.html#connection_Connection-readyState
    error: () => console.error('mongoose: error'),
    connected: () => console.log('mongoose: connected'),
    connecting: () => console.log('mongoose: connecting'),
    disconnecting: () => console.log('mongoose: disconnecting'),
    disconnected: () => console.log('mongoose: disconnected'),
  },
  useDefaultErrorHandler: false, // enable or disable the default error handler
};

// apply the middleware
app.use(mongoose(config));

// and you can now use the middleware via the ctx with
// `ctx.model(modelName)` and `ctx.document(modelName, document)`

Issues and Bugs

If you manage to find any, please report them here so they can be squashed.

Development and Contributing

Pull the repo and install dependencies with yarn

# run tests
yarn test

# lint source
yarn lint

# format source with prettier
yarn format

License

MIT, see the LICENSE file.

koa-mongoose's People

Contributors

south-paw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

koa-mongoose's Issues

MongoDB+SRV protocol?

I'm trying to convert over to using this so as to start the connection with the Koa server, etc., however, I noticed that you don't actually seem to support the mongodb+srv:// protocol, which is what's recommended/forced by MongoDB Atlas. Furthermore, their documentation is written such that it seems as though no other form is supported. Do you have any intent on supporting that form, and if not, how does one work around it?

Deprecation Warnings

Seeing these warnings

DeprecationWarning: The option `reconnectTries` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6
DeprecationWarning: The option `reconnectInterval` is incompatible with the unified topology, please read more by visiting http://bit.ly/2D8WfT6

Environment versions:

"mongodb": "^3.5.2",
"mongoose": "^5.8.10",
"@south-paw/koa-mongoose": "^1.1.0",

Question

Is there a way to interact with the db outside of koa's ctx? For instance, I want to do something like

var query = {'username': req.user.username};
req.newData.username = req.user.username;

MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
    if (err) return res.send(500, {error: err});
    return res.send('Succesfully saved.');
});

...but I do not have access to ctx.model where I want to update this. Any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.