MongoDB
Installation
Install the MongoDB package along with BuildMyMeta to integrate metadata logging with MongoDB.
npm install build-my-meta mongoose
# Or, using Yarn
yarn add build-my-meta mongoose
# Or, using pnpm
pnpm add build-my-meta mongoose
Database Structure
Metadata entries in MongoDB will have the following structure:
{
"userId": "string",
"apiMethod": "string",
"metadata": {
"action": "string",
"...": "any additional fields"
},
"status": "string",
"error": {
"message": "string",
"stack": "string"
},
"responseMessage": "string",
"responseTime": "number",
"ip": "string",
"userAgent": "string",
"headers": {
"...": "headers as key-value pairs"
},
"timestamp": "date"
}
Automatic Metadata Logging
Set up automatic metadata logging in MongoDB. Once configured, metadata will be automatically saved to MongoDB without manual intervention. The `userId` parameter is required in `BuildMyMeta` to identify users for metadata logs, but it can be modified on a per-API basis if needed.
const mongoose = require('mongoose');
const { BuildMyMeta, DB_TYPES } = require('build-my-meta');
// Initialize mongoose
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
// Use BuildMyMeta with automatic logging (set to true) and pass `userId`
app.use(BuildMyMeta(mongoose, DB_TYPES.MONGODB, true, 'defaultUserId'));
// API route example
app.post('/login', (req, res) => {
// Handle login
res.send('User logged in');
});
For a `POST` request to `/login`, here is an example of the metadata automatically saved in MongoDB:
{
"userId": "defaultUserId",
"apiMethod": "POST",
"metadata": {
"url": "/login",
"body": { "username": "exampleUser" },
"params": {},
"query": {}
},
"status": "200",
"responseMessage": "User logged in",
"responseTime": 123,
"ip": "127.0.0.1",
"userAgent": "Mozilla/5.0",
"headers": {
"content-type": "application/json"
},
"timestamp": "2024-11-11T06:30:19.002Z"
}
Manual Metadata Logging
Configure manual logging in MongoDB to control when and what metadata is saved. This allows customization of metadata entries using `LogCustomMetadata` and flexibility to modify metadata for specific conditions.
const mongoose = require('mongoose');
const { BuildMyMeta, LogCustomMetadata, DB_TYPES } = require('build-my-meta');
// Initialize mongoose
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
// Use BuildMyMeta with manual logging (set to false)
app.use(BuildMyMeta(mongoose, DB_TYPES.MONGODB, false, 'defaultUserId'));
// Manually log metadata
app.post('/login', (req, res, next) => {
let metadata = {
userId: 'user123', // Optional: Overrides defaultUserId for this request
apiMethod: 'POST',
metadata: { action: 'User login' },
status: 201,
};
// Call LogCustomMetadata with the initial metadata
LogCustomMetadata(metadata, req);
// Example condition: add extra information if the user is not found
if (!req.body.username) {
metadata.metadata.error = "Username is missing";
return next(new Error('Username is required'));
}
// Proceed with login processing...
res.send('User logged in');
});
In this example, metadata can be modified even after calling `LogCustomMetadata`. This allows dynamic updates to metadata based on conditions within the API logic.
For a `POST` request to `/login`, here’s an example of the metadata saved in MongoDB when additional fields are dynamically added:
{
"userId": "user123",
"apiMethod": "POST",
"metadata": {
"action": "User login",
"error": "Username is missing"
},
"status": "400",
"responseMessage": "Username is required",
"responseTime": 95,
"ip": "127.0.0.1",
"userAgent": "Mozilla/5.0",
"headers": {
"content-type": "application/json"
},
"timestamp": "2024-11-11T06:30:19.002Z"
}
Using `LogCustomMetadata` for Dynamic Metadata Updates
With `LogCustomMetadata`, you can modify the metadata after the initial function call to add specific information. Here’s how to use it effectively:
1. Define initial metadata: Define essential fields, including `apiMethod`, `metadata`, `status`, and optionally `userId`.
2. Modify metadata based on conditions: After calling `LogCustomMetadata(metadata, req)`, you can dynamically add to the metadata object based on your API logic.
3. Finalize the response: The metadata will automatically capture the final response details, including status and error, at the end of the request.
Metadata Logging to CSV Files
BuildMyMeta logs metadata to CSV files in your project folder under the directory `buildmymetalogs`. This directory contains four files:
`metaSuccess.csv` - Stores successfully logged metadata entries processed by BuildMyMeta.
`metaError.csv` - Stores metadata entries with errors or issues encountered during logging in BuildMyMeta.
`apiSuccess.csv` - Logs successful responses for user API calls.
`apiError.csv` - Logs error responses for user API calls.