Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import MongoDB using es6 style imports?

Tags:

Hopefully this is a simple question. I am trying to import MongoDB using the es6 import-from style. If I import using node require it works fine.

let mongo = require('mongodb'); let MongoClient = mongo.MongoClient; 

But if I import it the es6 way it breaks without errors or logs.

import {MongoClient} from 'mongodb'; 

But it doesn't break when compiling/running it only breaks when I try to do anything with MongoClient.

Here is my Db Manager class-

import {MongoClient} from 'mongodb';  export class DbManager {    constructor() {     console.log('Constructing DB Connection');   }  } 

When I run my server I get several logs from other managers and events.

mycomputer myuser$ ./start.sh Server Constructing Route Manager Constructing Initializing Route: Static Constructing DB Connection http server started on port: 8000 

But if I do a console.log of the MongoClient there is simply no output.

import {MongoClient} from 'mongodb';  export class DbManager {    constructor() {     console.log('Constructing DB Connection');     console.log(MongoClient);   }  } 

And the output looks like this-

mycomputer myuser$ ./start.sh mycomputer myuser$ 

There are no compile errors so I don't understand why this isn't working. Furthermore, I don't understand why there aren't any logs! This is one of the last things that happens, there should at least be logs up until that point I'd think. If you'd like to see my start.sh script here it is (quick and dirty, don't judge me):

tsc echo "var System = require('systemjs');" > dist/final.js babel dist/typescript.js >> dist/final.js echo "System.import('main');" >> dist/final.js node dist/final.js 

EDIT

Continuing to search for the answer while waiting (hoping) for a response. I'm taking a look at the resulting final.js and if MongoClient is used anywhere in the file the System.register function call looks like this-

System.register("db/db.manager", ["mongodb"] ... 

And if I don't use it (even if I import it) it does not show mongodb.

System.register("db/db.manager", [] ... 

That would explain why nothing would happen. Something is wrong with trying to import mongodb. Not sure yet what to do.

EDIT EDIT

Found a solution. One i'm not thrilled with but maybe it's just the way it has to be.

I don't think I can rely on es6 imports. It looks like I can use it to import the typedefs but not the actual module. How I got around this is like this-

import {Db as MongoDb, MongoClient} from 'mongodb'; let mongodb = require('mongodb'); let mongoClient: MongoClient = mongodb.MongoClient; 

A lot of extra work. If there's another way please let me know.

like image 430
micah Avatar asked Mar 12 '16 20:03

micah


People also ask

How do I import data into MongoDB?

To import data to a MongoDB database, you can use mongoimport to import specific collections data, or you can use mongorestore to import a binary (BSON) full database backup. The exported database file must be stored locally on the same machine as your client.

What is ES6 import?

Introduction to ES6 import:The import statement is used to import modules that are exported by some other module. A module is a file that contains a piece of reusable code. The import modules are in strict mode whether it is declared or not. Syntax of import: import name from 'module-name'

What is ES6 in node JS?

ECMAScript 2015 or ES6 is the term used to describe the latest stable iteration of the programing language commonly called JavaScript. ES6 is a significant update to the language, and the first update to the language since ES5 was standardized in 2009.


1 Answers

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. :)

like image 121
4Z4T4R Avatar answered Oct 06 '22 05:10

4Z4T4R