Skip to content

A no frills ES6 class to MongoDB document mapper.

License

Notifications You must be signed in to change notification settings

j/type-mongo-mapper

Repository files navigation

🔗 type-mongo-mapper

A @decorator based MongoDB document to ES6 class mapper.

travis codecov

type-mongo-mapper makes it easy to map javascript classes to MongoDB documents and back using @decorators.

Install

yarn add type-mongo-mapper

Usage

If you want to take advantage of an upcoming feature in mongodb, you must use [email protected] and higher. Otherwise, you can just use the "map" and "unmap" methods manually when dealing with plain documents. See this commit

Quickstart

import { Document, Field, mapper } from 'type-mongo-mapper';

@Document()
class User {
  @Field()
  public _id: ObjectID;

  @Field()
  public firstName: string;

  @Field()
  public lastName: string;

  get id(): string {
    return this._id.toHexString();
  }
}

const { map, unmap } = mapper(User);

// pass "map" & "umap" options to collection
const usersCollection = db.collection('users', { map, unmap });

// Document to User

const user = await usersCollection.findOne({ /* ... */ }) // user is an instanceof User

// Documents to Users

const users = await collection.find({ /* ... */ }); // each item in cursor will be a User


// Save a User.

const user = new User();
user.firstName = 'John';
user.lastName = 'Doe';

await collection.insertOne(user);

About

A no frills ES6 class to MongoDB document mapper.

Resources

License

Stars

Watchers

Forks

Packages

No packages published