Database Configuration
Now that your environment is set up, let’s configure the database using Noblex’s defaultDB
method.
This gives you a central place to initialize your MongoDB connection, apply default schema options, and register global model methods.
Paste the following code in src/db.ts
:
import * as env from "./env.js";
import { defaultDB, Types } from "noblex";
defaultDB({
uri: `mongodb://${env.DB_HOST}:${env.DB_PORT}/${env.DB_NAME}$`,
defaults: {
createdBy: { type: Types.ObjectId, ref: "User", default: null },
},
options: {
timestamps: true,
},
methods: {
find: async function (filter) {
// this.req is the current Request object
const data = this.model.find({deleted:false, ...filter});
return data;
},
},
});
What This Does
- Initializes the MongoDB connection using your
.env
variables. - Sets default schema fields like
createdBy
. - Enables timestamps for all models globally.
- Defines custom global methods accessible on every model.
Request Access for RBAC
You can access the current request object inside your global model methods using this.req
.
This is especially useful for implementing role-based access control (RBAC) directly within database logic.
methods: {
find: async function (filter) {
const user = this.req.user;
if (user.role !== "admin") {
return this.model.find({ createdBy: user.id , ...filter});
}
return this.model.find(filter);
},
}