简体   繁体   中英

How to import MongoDB using es6 style imports?

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.

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');

Try this:

import { default as mongodb } from 'mongodb';
let MongoClient = mongodb.MongoClient;

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 mongodb@4.0.0-beta.3

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

This works for me:

import mongodb from 'mongodb'
const { MongoClient } = mongodb

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;

I had no luck using import 'mongodb' , so I used require by importing createRequire .

import { createRequire } from 'module'
const require = createRequire(import.meta.url);
const { MongoClient } = require('mongodb');

I used this in a .mjs file, where require is not even defined, and it worked like a charm.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM