MongoDB Integration

Learn how to use @inceptools/db with MongoDB and Mongoose.

Setup

First, make sure you have MongoDB and Mongoose installed:

npm install mongoose mongodb

Basic Usage

Here's how to use @inceptools/db with MongoDB:

import { MongoService, SUPPORTED_DBS } from "@inceptools/db";
import mongoose from "mongoose";

// Define your MongoDB schemas
const schemas = {
  users: new mongoose.Schema({
    name: String,
    email: String,
    createdAt: { type: Date, default: Date.now },
  }),
  posts: new mongoose.Schema({
    title: String,
    content: String,
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'users' },
    createdAt: { type: Date, default: Date.now },
  }),
};

// Create a MongoDB service instance
const mongoService = new MongoService({
  type: SUPPORTED_DBS.MONGO_DB,
  connectionString: "mongodb://localhost:27017/myapp",
  models: schemas,
});

// Connect to MongoDB
await mongoService.connect();

// Use your models
const newUser = await mongoService.users.create({
  name: "John Doe",
  email: "[email protected]",
});

const users = await mongoService.users.find();

// Create a post with reference to a user
const newPost = await mongoService.posts.create({
  title: "My First Post",
  content: "Hello world!",
  author: newUser._id,
});

// Find posts with populated author
const posts = await mongoService.posts.find().populate('author');

// Close the connection when done
await mongoService.closeConnection();

Advanced Configuration

You can pass additional Mongoose connection options:

const mongoService = new MongoService({
  type: SUPPORTED_DBS.MONGO_DB,
  connectionString: "mongodb://localhost:27017/myapp",
  models: schemas,
  configOptions: {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    maxPoolSize: 10,
    serverSelectionTimeoutMS: 5000,
  },
});

Transactions

Working with MongoDB transactions:

// Start a session
const session = await mongoService.connection.startSession();

try {
  // Start a transaction
  session.startTransaction();

  // Perform operations
  const user = await mongoService.users.create([{ name: "Jane Doe", email: "[email protected]" }], { session });
  const post = await mongoService.posts.create([{ title: "Jane's Post", content: "Hello!", author: user[0]._id }], { session });

  // Commit the transaction
  await session.commitTransaction();
} catch (error) {
  // Abort the transaction on error
  await session.abortTransaction();
  throw error;
} finally {
  // End the session
  session.endSession();
}

Next Steps