Mongoose plugin for hapi-based servers. Supports connecting to one or multiple databases and look up and register models by connection. Optionally, aliases can be created to reference connections. The plugin options are:
options
- aconnection
or an array ofconnection
s where:connection
- an object containing:uri
- a mongo urialias
- (optional) a database name alias which is only used to reference the connection when multiple are created. otherwise ignored.loadSchemasFrom
- (optional) an array of globs from where schemas will be loaded. matching files must export amongoose.Schema
object or a function with the signatureasync function(server)
returning a schema.options
- (optional) options passed tomongoose
createConnection method. unknown properties are allowed:auth
- an object with auth credentialsuser
password
autoIndex
bufferCommands
connections
- an array ofconnection
objects as described above.
Connection and models are accessible under the server.app.mongo
property. When multiple connections are created the database name or alias
is used as namespace for accessing each database properties.
Models are named as the filename matching the schema pattern. Model name first letter is capitalized by default. e.g. Animal
.
const plugin = {
plugin: require('hapi-mongoose2'),
options: {
connections: [
{
uri: 'mongodb://localhost:27017/myapp'
},
{
alias: 'safebox',
uri: 'mongodb://localhost:27017/secrets',
loadSchemasFrom: [
'src/schemas',
'!.{md,json}'
],
options: {
auth: {
user: 'admin',
password: 'pa55w0rd'
},
autoIndex: false,
bufferCommands: true
}
}
]
}
};
const server = new Hapi.server();
await server.register(plugin);
// Using database `secrets`:
const { Admin } = server.app.mongo.safebox.models;
await Admin.create({ name: 'Quentin', last: 'Tarantino' });
await server.app.mongo.safebox.connection.close();
"mongoose": ">=5.0.0",
"hapi": ">=17.0.0"