3.0.0 • Published 2 years ago

mongodb-typescript v3.0.0

Weekly downloads
469
License
ISC
Repository
github
Last release
2 years ago

mongodb-typescript

Hydrate MongoDB documents into TypeScript-defined objects

Motivation

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: 1. objects returned by 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. 2. there is not easy way to reference other collections. In a noSQL database relations should be avoided, but we all know this is not always a viable option. In such case we define a field with id referencing some other collection and then make separate request to retrieve referenced entity and append it to referencing entity. This is tedious and not easy to explain well to TypeScript's static typing. 3. class definitions should reflect database schema. In particular: we want to use a property decorator to define database indexes

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.

Install

$ npm install mongodb-typescript

Make sure to enable emitDecoratorMetadata and experimentalDecorators in tsconfig.json

Quick start

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());

Reference

Entity definition

@id

Required. Defines primary id that will be used as _id of the mongo collection.

class Post {
  @id myId: ObjectId;
}

@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;
}

@nested

Used to mark nested entity or array of entities.

Parameter
typeFunctionFunction 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." }
  ]
}

@ignore

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"
}

@ref

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
refIdOptional. 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;
}

@index

Used to define an index on a field.

does not actually create the index. Use Repository.createIndexes to do so.

Parameters:

parameter
typeType 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
optionsOptional. SimpleIndexOptions. See table below, SimpleIndexOptions interface or mongodb docs

SimpleIndexOptions:

fieldtype
namestringName of the index. Defaults to field name.
backgroundboolean
uniqueboolean
partialFilterExpressiondocument
sparseboolean
expireAfterSecondsnumber
storageEnginedocument
weightsdocument
default_languagestring
language_overridestring
textIndexVersionnumber
2dsphereIndexVersionnumber
bitsnumber
minnumber
maxnumber
bucketSizenumber
collationObject

Example usage:

class User {
  ...
  @index(1, { unique: true, sparse: true, name: 'email_unique_index' }) email: string;

  @index() someId: number;
}

@indexes

Used to define an indexes on a entity (most likely compound).

does not actually create the index. Use Repository.createIndexes to do so.

Parameters:

parametertype
indexesIndexOptions[]

IndexOptions:

fieldtype
namestringRequired. Name of the index
keydocumentA 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

Repository

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.

constructor

parametertype
entitytypetype of stored entities. Must equal T
mongoClientMongoClientmongo client to use for all requests
collectionstringname of collection to reference

c

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.

count

TODO

createIndexes

TODO

insert

TODO

update

parametertype
entityObjectEntity to update, must be of type T
optionsReplaceOneOptionsOptions to pass to the underlying replaceOne call
await userRepo.update(post);
await userRepo.update(post, { upsert: true });

save

TODO

findOne

TODO

findById

TODO

findManyById

TODO

find

TODO

populate

TODO

await userRepo.populate(post, 'author');

populateMany

TODO

hydrate

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.

dehydrate

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.

Inspired by Typegoose and TypeORM

3.0.0

2 years ago

2.2.1

4 years ago

2.2.0

4 years ago

2.1.0

4 years ago

2.0.4

5 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.5.1

6 years ago

1.5.0

6 years ago

1.4.4

6 years ago

1.4.3

6 years ago

1.4.2

6 years ago

1.4.1

6 years ago

1.4.0

6 years ago

1.3.0

6 years ago

1.2.3

6 years ago

1.2.2

6 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.0

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago