How to import MongoDB using es6 style imports?
Asked Answered
I

5

35

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.

Issykkul answered 12/3, 2016 at 20:26 Comment(2)
Yes it does look like you can import typedefs but not the actual module. That is actually the intent since it is not the same thing as what the require system does.Ivelisseivens
For me ``` import * as mongodb from 'mongodb'; const MongoClient = mongodb.default.MongoClient; ``` works. This is article about implementing es6 modules in node packages medium.com/@dandv/…Cleavland
I
18

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

Inestimable answered 5/3, 2021 at 6:9 Comment(2)
You are awesome. This is the least confusing answer.Heidt
You're no slouch either, @Heidt Thank you for the kind vote of confidence.Inestimable
S
11
import { MongoClient } from 'mongodb';

just imports type definition from node_modules/@types/mongodb/index.d.ts

import * as mongodb from 'mongodb';

imports everything from node_modules/mongodb/index.js and its the same as

let mongodb = require('mongodb');
Sherwin answered 3/6, 2017 at 8:7 Comment(3)
i am currently importing specific packages from mongodb, ie const MongoClient = require('mongodb').MongoClient and const ObjectID = require('mongodb').ObjectID would the method you suggested increase codebase size because it was importing all the packages from mongodb, as opposed to just some of them?Monoacid
const MongoClient = require('mongodb').MongoClient does not mean that you import only specific packages. You are reading the whole library and store part of it in constant called MongoClient .Sherwin
It works perfectly fine (thanks!) but I cannot wrap my head around the way node is able to interpret 'mongodb' as node_modules/@types/mongodb/index.d.ts on one line and then as node_modules/mongodb/index.js on the other. Can anyone explain it, pls?Candracandy
J
5

Try this:

import { default as mongodb } from 'mongodb';
let MongoClient = mongodb.MongoClient;
Jungian answered 30/6, 2019 at 1:21 Comment(0)
B
3

Edit

As Elihu pointed out in the comment below, the additional integration of @types/mongo is now deprecated and is no longer needed as the mongo-package now comes with types per default.

npm install --save mongodb is therefore sufficient.

Original Answer

As mkalmo suggested you can import the mongodb types:

Step 1: Install via the npm mongodb types package
npm install --save @types/mongodb

Step 2: Use it!

import mongodb from "mongodb";
const MongoClient = mongodb.MongoClient;
Blepharitis answered 22/11, 2020 at 18:49 Comment(1)
types are deprecated npmjs.com/package/@types/mongodbMarquess
P
-1

This works for me:

import mongodb from 'mongodb'
const { MongoClient } = mongodb
Ptisan answered 2/3, 2020 at 12:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.