type-mongo-mapper
v0.0.6
Published
A no frills ES6 class to MongoDB document mapper.
Downloads
3
Readme
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);