How to import MongoDB using es6 style imports?

Listen, I know there are more than a handful of cracks at this solution here. Some may work for you, but for me, none solved me but the one below.

2021 UPDATE:

BORING BACKSTORY ALERT

We’re using Node v14.16.0 and our package.json has "type": "module" set. So, our code is ES6+ and commonjs imports are a deal-breaker in most cases, especially when it comes to the MongoDB Native 3.6 NodeJS Driver.

Lucky for us, MongoDB Native ^4.0.0-beta.3 is written in TypeScript, and works as expected. Prepare your shattered sprits for liftoff. 😉 Oh, and rather than store your secret sauce (user:pass and uri) in your source code, check out node-config and be safe.

THE SOLUTION

# This version will keep changing after this posts, so take heed.
$ cd path/to/your/project
$ npm i -s [email protected]

Inside your project:

import config from 'config'
// MongoDB
import { MongoClient } from 'mongodb'
const client = new MongoClient(config.get('mongodb.uri'))
await client.connect()
const db = client.db()
const stuff = db.collection('AllTheStuff')
const record = {
  type: "ThisAndThat",
  lastUpdated: new Date().getTime()
}
const query = { type: "ThisAndThat" }
const options = { upsert: true }
const result = await stuff.replaceOne(query, record, options)

And now all your cats are sleep silent tonight. Hopefully this lowers the level of unchallenged insanity in the world, or helps you in your quest, whichever suits your taste in achievement. 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)