
Security News
ESLint Adds Official Support for Linting HTML
ESLint now supports HTML linting with 48 new rules, expanding its language plugin system to cover more of the modern web development stack.
mongodb-typescript
Advanced tools
Hydrate MongoDB documents into TypeScript-defined objects
When using MongoDB with TypeScript we usually want to save our "strongly-typed" entities into database collection and then retrieve them back at some later time. During this we face three major difficulties:
mongodb
driver are plain objects. This means that if we have saved an object with some functions, these functions will not be saved and will not be present on the retrieved document. If we were to assign all properties of received object to a properly TypeScript-typed object, we would have to do this recursively, since some properties can also be typed objects and have own functions.This package strives to facilitate at these points by wrapping official mongodb
package. It utilizes class-transformer
package to hydrate and de-hydrate plain object into classed objects and vice-versa.
It may seem that it is a TypeScript equivalent to mongoose
package, but this is not the case, since it does not provide any validation, stripping of non-defined properties or middleware.
This package is trying to be as non-restrictive as possible and to let the developer access underlying mongodb
functions and mechanism (such as cursors) while still providing hydration, population and schema reflection.
$ npm install mongodb-typescript
Make sure to enable emitDecoratorMetadata
and experimentalDecorators
in tsconfig.json
import { id, Repository } from 'mongodb-typescript';
// define your entity
class User {
@id id: ObjectId;
name: string;
age: number = 15;
hello() {
return `Hello, my name is ${this.name} and I am ${this.age} years old`;
}
}
const repository = new Repository<User>(User, mongodbClient);
// create new user entity (MongoDB document)
const user = new User();
user.name = 'tom';
await userRepo.insert(user);
// prints "User { id: 5ba2648a6f74af5def444491, name: 'tom', age: 15 }"
console.log(user);
// now let's retrieve entity from database
const saved = await userRepo.findById(user.id);
// prints `Hello, my name is tom and I am 15 years old`
console.log(saved.hello());
Required. Defines primary id that will be used as _id
of the mongo collection.
class Post {
@id myId: ObjectId;
}
All properties except ones decorated with @id
that are of type ObjectId (from bson
package) must have @objectId
because underlying package class-transformer
does not handle it correctly.
class Post {
...
@objectId authorId: ObjectId;
}
Used to mark nested entity or array of entities.
Parameter | |
---|---|
typeFunction | Function that returns type of nested entity |
Example usage:
class Texts {
main: string;
doc: string;
}
class Comment {
text: string;
}
class Post {
@id id: ObjectId;
title: string;
@nested(() => Texts) text: Texts;
@nested(() => Comment) comments: Comment[]
}
This would represent following mongo document:
{
"_id": ObjectId("5b27c8da65ec1b5c0c0e8ed4"),
"title": "My new post",
"timestamps": {
"postedAt": ISODate("2018-09-15T10:50:38.718Z"),
"lastUpdateAt": ISODate("2018-09-15T10:50:38.718Z"),
},
"comments": [
{ "text": "This is good." },
{ "text": "This is bad." }
]
}
Used to mark a property as ignored so it will not ba saved in the database.
Example usage:
class User {
@id id: ObjectId;
name: string;
@ignore onlyImportantAtRuntime: number;
}
This would represent following mongo document:
// user
{
"_id": ObjectId("5b27d15bfab97f681aac2862"),
"name": "gregory"
}
Used to define an entity or array of entities that will not be saved into another collection and only have a key or array of keys saved on referencing entity's collection.
This key will be saved in a field named {@ref field name}Id
or {@ref field name}Ids
.
To access this key directly or apply a custom name you can pass a parameter with name of your key field. See example below.
Parameter | |
---|---|
refId | Optional. Name of field should hold referencing key |
Example usage:
class User {
@id id: ObjectId;
name: string;
}
class Post {
@id id: ObjectId;
title: string;
@ref() author: User;
}
This would represent following mongo documents:
// post
{
"_id": ObjectId("5b27c8da65ec1b5c0c0e8ed4"),
"title": "My new post",
"authorId": ObjectId("5b27d15bfab97f681aac2862")
}
// user
{
"_id": ObjectId("5b27d15bfab97f681aac2862"),
"name": "gregory"
}
Custom referencing key:
class Post {
...
@objectId author_key: ObjectId;
@ref('author_key') author: User;
}
Used to define an index on a field.
does not actually create the index. Use Repository.createIndexes to do so.
Parameters:
parameter | |
---|---|
type | Type of index. Use 1 or -1 for ascending or descending order, respectively. Use string value for other index types (eg. '2dsphere' for geo spacial index). Defaults to 1 |
options | Optional. SimpleIndexOptions. See table below, SimpleIndexOptions interface or mongodb docs |
SimpleIndexOptions:
field | type | |
---|---|---|
name | string | Name of the index. Defaults to field name. |
background | boolean | |
unique | boolean | |
partialFilterExpression | document | |
sparse | boolean | |
expireAfterSeconds | number | |
storageEngine | document | |
weights | document | |
default_language | string | |
language_override | string | |
textIndexVersion | number | |
2dsphereIndexVersion | number | |
bits | number | |
min | number | |
max | number | |
bucketSize | number | |
collation | Object |
Example usage:
class User {
...
@index(1, { unique: true, sparse: true, name: 'email_unique_index' }) email: string;
@index() someId: number;
}
Used to define an indexes on a entity (most likely compound).
does not actually create the index. Use Repository.createIndexes to do so.
Parameters:
parameter | type |
---|---|
indexes | IndexOptions[] |
IndexOptions:
field | type | |
---|---|---|
name | string | Required. Name of the index |
key | document | A document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field. For an ascending index on a field, specify a value of 1; for descending index, specify a value of -1. See mongodb documentation |
... | All properties of SimpleIndexOptions |
Reference to mongodb
collection that handles hydration and de-hydration of documents into entities and vice-versa.
Repository is a generic class that requires type parameter T should be type of entity that is stored in referenced collection.
Different repositories may reference collections in different databases at different hosts.
parameter | type | |
---|---|---|
entity | type | type of stored entities. Must equal T |
mongoClient | MongoClient | mongo client to use for all requests |
collection | string | name of collection to reference |
mongodb
collection used to make all the requests to the database.
Can be used to access all features of mongodb, but returns non-hydrated (plain) objects.
TODO
TODO
TODO
parameter | type | |
---|---|---|
entity | Object | Entity to update, must be of type T |
options | ReplaceOneOptions | Options to pass to the underlying replaceOne call |
await userRepo.update(post);
await userRepo.update(post, { upsert: true });
TODO
TODO
TODO
TODO
TODO
TODO
await userRepo.populate(post, 'author');
TODO
Converts a plain object from database into typed entity with functions, typed nested entities and correctly named _id field.
Use this function when fetching documents via vanilla mongodb
collection.
Returns plain object that can be saved to database. It handles custom _id names and dereferences objects (removes referenced objects and sets referencing keys).
This is a standalone function and does not require associated repository.
FAQs
Hydrate MongoDB documents into TypeScript-defined objects
The npm package mongodb-typescript receives a total of 90 weekly downloads. As such, mongodb-typescript popularity was classified as not popular.
We found that mongodb-typescript demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
ESLint now supports HTML linting with 48 new rules, expanding its language plugin system to cover more of the modern web development stack.
Security News
CISA is discontinuing official RSS support for KEV and cybersecurity alerts, shifting updates to email and social media, disrupting automation workflows.
Security News
The MCP community is launching an official registry to standardize AI tool discovery and let agents dynamically find and install MCP servers.