Skip to content

Instantly share code, notes, and snippets.

@mugan86
Last active April 10, 2020 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mugan86/63f6b2d40aa9c52aa4f0e5ac1e69b953 to your computer and use it in GitHub Desktop.
Save mugan86/63f6b2d40aa9c52aa4f0e5ac1e69b953 to your computer and use it in GitHub Desktop.
Database operations
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