Last active
April 10, 2020 23:51
-
-
Save mugan86/63f6b2d40aa9c52aa4f0e5ac1e69b953 to your computer and use it in GitHub Desktop.
Database operations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Db } from 'mongodb'; | |
export const asignDocumentId = async ( | |
database: Db, | |
collection: string, | |
sort: object = { registerDate: -1 } | |
) => { | |
// Check las | |
const lastItem = await database | |
.collection(collection) | |
.find() | |
.limit(1) | |
.sort(sort) | |
.toArray(); | |
if (lastItem.length === 0) { | |
return 1; | |
} | |
return lastItem[0].id + 1; | |
}; | |
export const findOneElement = async ( | |
database: Db, | |
collection: string, | |
filter: object | |
) => { | |
return await database.collection(collection).findOne(filter); | |
}; | |
export const insertOneElement = async ( | |
database: Db, | |
collection: string, | |
document: object | |
) => { | |
return await database | |
.collection(collection) | |
.insertOne(document); | |
}; | |
export const insertManyElement = async ( | |
database: Db, | |
collection: string, | |
documents: Array<object> | |
) => { | |
return await database | |
.collection(collection) | |
.insertMany(documents); | |
}; | |
export const listElements = async ( | |
database: Db, | |
collection: string, | |
filter: object | |
) => { | |
return await database.collection(collection).find(filter).toArray(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment