CAROLINA DOCS


DB

The "db" app's service manages a database connection to a MongoDB database and access to a collection of mongoose models.

The DB Service

When the "db" service is loaded, it attempts to create a connection to a MongoDB as configured (by default at mongodb://localhost/main).

The "db" service also loads the file models.js from every installed app if it exists, and maintains a library of mongoose models which you can access via the model method. For example to get the "User" model (defined by the "auth" app):

async someFunction() {

const User = App.$db.model('User');
let u = await User.findOne({ username: "admin" }).exec();

// do something with admin user
}

Configuration

The "db" app has the following default configuration:


module.exports = {
mongoHost: process.env.MONGO_HOST || 'localhost',
mongoDb: process.env.MONGO_DB || 'main'
};

You can overwrite these either in config/db.js or by simply providing the indicated environment variables in .env.

Publishable Files

You can publish the default db config config/db.js:

node . publish --config db

Defining Model Schemas

You can add models to the "db" service by adding a models.js to your app. It should export an object mapping unique names to mongoose schemas. The "db" service will create the actual models, add them to the mongoose connection, and have them available.

Example:

// apps/my_custom_app/models.js

const mongoose = require('mongoose');

const ImportantStringSchema = new mongoose.Schema({
key: { type: String, index: true },
value: String
}, { collection: 'important_string' });

module.exports = {
ImportantString: ImportantStringSchema
};

NOTE: Due to some error with current mongoose version, when multiple packages import their own mongoose, there is often an error regarding document[thisisselected] that comes up when unique constraints are applied. This should be fixed soon, but in the meantime it may be worth avoiding the unique constraint on a field.

Given the above file, elsewhere in your project you should be able to access the "ImportantString" model:

router.get('/some/route', asyncHandler(async (req, res) => {
const ImportantString = App.$db.model('ImportantString');
let welcome = await ImportantString.findOne({ key: "WELCOME" }).exec();
}));

CAROLINA DOCS