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 adapterModel
Collection | Promise<Collection>
required
MongoDB collection instance or a promise that resolves to one
Name of the id field property
Pagination settings with default and max page size
Allow multiple updates. Can be true, false, or an array of method names like ['create', 'patch', 'remove']
If true, disables automatic ObjectId conversion for the id field
useEstimatedDocumentCount
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?)
Query filters including $limit, $skip, $sort, $select, and MongoDB query operators
paginate
PaginationOptions | false
Override pagination settings for this call
MongoDB aggregation pipeline stages
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?)
The document id to retrieve
create
Create one or more new documents.
await service.create(data, params?)
Document data to create. Can be a single object or array of objects
mongodb
InsertOneOptions | BulkWriteOptions
MongoDB-specific insert options
update
Completely replace a document.
await service.update(id, data, params?)
The document id to update
Complete document data to replace with
MongoDB-specific replace options
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
Partial data to merge with existing document(s). Supports MongoDB update operators like $set, $inc, etc.
Query to filter which documents to patch (when id is null)
MongoDB-specific update options
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
Query to filter which documents to remove (when id is null)
mongodb
FindOneAndDeleteOptions | DeleteOptions
MongoDB-specific delete options
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)
The converted id (ObjectId if applicable)
getModel
Retrieve the MongoDB collection instance.
const collection = await adapter.getModel(params?)
aggregateRaw
Execute a MongoDB aggregation pipeline.
const cursor = await adapter.aggregateRaw(params)
params
MongoDBAdapterParams
required
Aggregation pipeline stages. Use { $feathers: true } as a stage marker to inject Feathers query filters
MongoDB aggregation cursor
findRaw
Execute a MongoDB find query without processing results.
const cursor = await adapter.findRaw(params)
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: '[email protected]',
name: 'Test User',
age: 25
})
const results = await users.find({
query: {
age: { $gte: 18 },
$sort: { name: 1 }
}
})