Skip to main content
The MongoDB adapter provides a service interface for MongoDB databases using the official MongoDB Node.js driver.

Installation

npm install @feathersjs/mongodb mongodb

MongoDBService

The main service class for MongoDB operations.

Constructor

import { MongoDBService } from '@feathersjs/mongodb'

const service = new MongoDBService<Result, Data, ServiceParams, PatchData>(options)
options
MongoDBAdapterOptions
required
Configuration options for the MongoDB adapter
Model
Collection | Promise<Collection>
required
MongoDB collection instance or a promise that resolves to one
id
string
default:"_id"
Name of the id field property
paginate
PaginationParams
Pagination settings with default and max page size
multi
boolean | string[]
Allow multiple updates. Can be true, false, or an array of method names like ['create', 'patch', 'remove']
disableObjectify
boolean
If true, disables automatic ObjectId conversion for the id field
useEstimatedDocumentCount
boolean
If true, uses MongoDB’s estimatedDocumentCount instead of countDocuments for better performance

Service Methods

find

Retrieve multiple documents from the collection.
await service.find(params?)
params
MongoDBAdapterParams
query
AdapterQuery
Query filters including $limit, $skip, $sort, $select, and MongoDB query operators
paginate
PaginationOptions | false
Override pagination settings for this call
pipeline
Document[]
MongoDB aggregation pipeline stages
mongodb
FindOptions
Additional MongoDB-specific find options
result
Paginated<Result> | Result[]
Returns paginated results or an array depending on pagination settings

get

Retrieve a single document by id.
await service.get(id, params?)
id
Id | ObjectId
required
The document id to retrieve
params
MongoDBAdapterParams
Query parameters
result
Result
The found document

create

Create one or more new documents.
await service.create(data, params?)
data
Data | Data[]
required
Document data to create. Can be a single object or array of objects
params
MongoDBAdapterParams
mongodb
InsertOneOptions | BulkWriteOptions
MongoDB-specific insert options
result
Result | Result[]
The created document(s)

update

Completely replace a document.
await service.update(id, data, params?)
id
Id | ObjectId
required
The document id to update
data
Data
required
Complete document data to replace with
params
MongoDBAdapterParams
mongodb
FindOneAndReplaceOptions
MongoDB-specific replace options
result
Result
The updated document

patch

Partially update one or multiple documents.
await service.patch(id, data, params?)
id
Id | ObjectId | null
required
The document id to patch, or null to patch multiple documents
data
PatchData
required
Partial data to merge with existing document(s). Supports MongoDB update operators like $set, $inc, etc.
params
MongoDBAdapterParams
query
AdapterQuery
Query to filter which documents to patch (when id is null)
mongodb
FindOneAndUpdateOptions
MongoDB-specific update options
result
Result | Result[]
The patched document(s)

remove

Remove one or multiple documents.
await service.remove(id, params?)
id
Id | ObjectId | null
required
The document id to remove, or null to remove multiple documents
params
MongoDBAdapterParams
query
AdapterQuery
Query to filter which documents to remove (when id is null)
mongodb
FindOneAndDeleteOptions | DeleteOptions
MongoDB-specific delete options
result
Result | Result[]
The removed document(s)

MongoDbAdapter

The base adapter class that MongoDBService extends. Provides internal methods prefixed with _ that bypass hooks.

Methods

getObjectId

Converts an id value to an ObjectId if appropriate.
const objectId = adapter.getObjectId(id)
id
Id | ObjectId
required
The id value to convert
result
Id | ObjectId
The converted id (ObjectId if applicable)

getModel

Retrieve the MongoDB collection instance.
const collection = await adapter.getModel(params?)
result
Collection
The MongoDB collection

aggregateRaw

Execute a MongoDB aggregation pipeline.
const cursor = await adapter.aggregateRaw(params)
params
MongoDBAdapterParams
required
pipeline
Document[]
Aggregation pipeline stages. Use { $feathers: true } as a stage marker to inject Feathers query filters
result
AggregationCursor
MongoDB aggregation cursor

findRaw

Execute a MongoDB find query without processing results.
const cursor = await adapter.findRaw(params)
result
FindCursor
MongoDB find cursor

Query Syntax

The MongoDB adapter supports Feathers query syntax and MongoDB-specific operators.

Standard Query Operators

// Find users older than 18
await service.find({
  query: {
    age: { $gt: 18 }
  }
})

// Find users with specific ids
await service.find({
  query: {
    _id: { $in: [id1, id2, id3] }
  }
})

// Complex queries with $and/$or
await service.find({
  query: {
    $or: [
      { status: 'active' },
      { role: 'admin' }
    ]
  }
})

Special Query Parameters

await service.find({
  query: {
    age: { $gte: 18 },
    $select: ['name', 'email'],  // Select specific fields
    $sort: { createdAt: -1 },     // Sort by createdAt descending
    $limit: 10,                    // Limit to 10 results
    $skip: 20                      // Skip first 20 results
  }
})

Aggregation Pipeline

Use the pipeline parameter for complex aggregations:
await service.find({
  pipeline: [
    { $match: { status: 'active' } },
    { $group: { _id: '$category', count: { $sum: 1 } } },
    { $feathers: true }, // Inject Feathers filters here
    { $sort: { count: -1 } }
  ]
})

MongoDB Update Operators in patch

// Increment a counter
await service.patch(id, {
  $inc: { views: 1 }
})

// Set specific fields
await service.patch(id, {
  $set: { status: 'published' },
  $push: { tags: 'new-tag' }
})

// Regular patch (auto-wrapped in $set)
await service.patch(id, {
  name: 'Updated Name'
})

ObjectId Converters

Utility functions for working with MongoDB ObjectIds in schemas.

resolveObjectId

Convert a string, number, or ObjectId to ObjectId.
import { resolveObjectId } from '@feathersjs/mongodb'

const objectId = await resolveObjectId('507f1f77bcf86cd799439011')

resolveQueryObjectId

Convert ObjectId query parameters including $in, $nin, $ne.
import { resolveQueryObjectId } from '@feathersjs/mongodb'

const query = await resolveQueryObjectId({
  $in: ['507f1f77bcf86cd799439011', '507f1f77bcf86cd799439012']
})

keywordObjectId

Ajv keyword for automatic ObjectId conversion in schemas.
import { keywordObjectId } from '@feathersjs/mongodb'
import Ajv from 'ajv'

const ajv = new Ajv()
ajv.addKeyword(keywordObjectId)

const schema = {
  type: 'object',
  properties: {
    userId: { type: 'string', objectid: true }
  }
}

Example

import { MongoDBService } from '@feathersjs/mongodb'
import { MongoClient } from 'mongodb'

interface User {
  _id?: ObjectId
  email: string
  name: string
  age: number
}

const client = await MongoClient.connect('mongodb://localhost:27017/mydb')
const db = client.db()

class UserService extends MongoDBService<User> {
  async create(data: Partial<User>, params?: any) {
    // Custom validation
    if (!data.email) {
      throw new Error('Email is required')
    }
    return super.create(data, params)
  }
}

const users = new UserService({
  Model: db.collection('users'),
  paginate: {
    default: 10,
    max: 50
  }
})

// Use the service
const user = await users.create({
  email: 'test@example.com',
  name: 'Test User',
  age: 25
})

const results = await users.find({
  query: {
    age: { $gte: 18 },
    $sort: { name: 1 }
  }
})