Skip to content

Instantly share code, notes, and snippets.

@aigoncharov
Created October 13, 2017 16:12
Show Gist options
  • Save aigoncharov/0c47052631f16df3732cc9e766a2e754 to your computer and use it in GitHub Desktop.
Save aigoncharov/0c47052631f16df3732cc9e766a2e754 to your computer and use it in GitHub Desktop.
Mongodb: insert and update generics example
import { Collection, Db } from 'mongodb'
interface IEntity {
field: string
}
interface IUpdate<T> {
$set: T
}
class MongoDB {
public db: Db;
public collection(): Collection<IEntity> {
return this.db.collection('collection');
}
}
const db = new MongoDB()
// This generics definition will allow us to check if a type of an incoming DTO matches our model
// I understand that MongoB is schemaless by default, but usually we still want to ensure some ind of schema
interface IDTO {
field: string
}
// without generics
async function ctrl (dto: DTO) {
const doc: IEntity = dto
await db.collection().insertOne(doc)
}
// with generics
async function ctrlNew (dto: DTO) {
await db.collection().insertOne<IEntity>(dto)
}
const res1 = db.collection().insertOne<IEntity>({field: 'a'})
const res1a = db.collection().insertOne({})
const res2 = db.collection().insertMany<IEntity>([{field: 'a'}])
const res2a = db.collection().insertMany([{}])
const res3 = db.collection().updateOne<IUpdate<IEntity>>({}, {$set: {field: 'a'}})
const res3a = db.collection().updateOne({}, {})
const res4 = db.collection().updateMany<IUpdate<IEntity>>({}, {$set: {field: 'a'}})
const res4a = db.collection().updateMany({}, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment