Cover image

My collection of JS/TS snippets

← Back to list
Last updated: June 10, 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.

# Mongo

# 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();
console.log(result);
} finally {
await client.close();
}
}
run().catch(console.dir);
📃 Copy
The code is licensed under the MIT license
Sergei Gannochenko
Sergei Gannochenko
Business-focused product engineer,  in ❤️ with amazing products 
AI, Golang/Node, React, TypeScript,  Docker/K8s, AWS/GCP, NextJS 
20+ years in dev