My collection of JS/TS snippets

← Back to list
Posted on 10.06.2020
Image by Marcin Wichary on Flickr

Here I have a collection of useful JS/TS snippets used in profession day to day work routine.


Connect to a database and retrieve data from a collection

While crawling the official docs, could not find a working example of how to extract data from a database. The snippet below is basically a compilation of some posts from Stackoverflow:

#!/usr/bin/env node
const MongoClient = require('mongodb').MongoClient;
const MONGO_URI = 'mongodb://localhost:27017/?maxPoolSize=20&w=majority';
const client = new MongoClient(MONGO_URI);
async function run() {
try {
const connection = await client.connect();
const database = connection.db('db_name');
const registry = database.collection('collection_name');
const result = await registry.find({}).toArray();
} finally {
await client.close();
The code is licensed under the MIT license


Sergei Gannochenko

Business-oriented fullstack engineer, in ❤️ with Tech.
Golang, React, TypeScript, Docker, AWS, Jamstack.
15+ years in dev.