1

when i use require commonjs everything is working

const { Schema, connect } = require("mongoose");

connect("mongodb://localhost:27017/usersdb", {
  useNewUrlParser: true
});

but when i use import es6 i get error

import { connect } from "mongoose";

connect(
  "mongodb://localhost:27017/usersdb",
  {
    useNewUrlParser: true
  }
);

SyntaxError: The requested module >'file:///C:/Users/Rich%20Warrior/Desktop/mon0022/node_modules/mongoose/index>.js' does not provide an export named 'connect'

and if you write like that

import * as mongoose from "mongoose";

mongoose.connect("mongodb://localhost:27017/usersdb", {
  useNewUrlParser: true
});

TypeError: mongoose.connect is not a function

package.json

{
  "name": "dur",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon -r esm src/index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "esm": "^3.2.25",
    "express": "^4.17.1",
    "i": "^0.3.6",
    "mongoose": "^5.7.8",
    "nodemon": "^1.19.4"
  }
}

I want to use the es6 module.Is there a way to use es6 modules with mongoose without getting an error?

Edgar
  • 6,022
  • 8
  • 33
  • 66
  • look here: https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node – Mischa Nov 08 '19 at 12:15
  • Does this answer your question? [How can I use an es6 import in node?](https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node) – Mischa Nov 08 '19 at 12:16
  • Have you tried `import mongoose from "mongoose";` ? The error seems pretty clear that there is no **named** export `connect`. So `import * as mongoose from "mongoose";` won't help either since it only imports named exports. – Felix Kling Nov 08 '19 at 12:16
  • @FelixKling why here is `import mongoose, {connect} from" mongoose ";` doesn’t work – Edgar Nov 08 '19 at 12:30
  • 1
    I'm not sure I understand the question. `import mongoose, {connect} from" mongoose ";` doesn't work because you are again trying to import an export named `connect` which does not exist. As I said, try `import mongoose from "mongoose";` and then access it with `mongoose.connect`. – Felix Kling Nov 08 '19 at 14:26

1 Answers1

1

NodeJS doesn't support it yet. You will have to use something like bable. Check this out from NodeJS doc as well.

Shihab
  • 2,641
  • 3
  • 21
  • 29
  • 1
    If that was the problem then the OP would get a different error. The error "does not provide an export named 'connect'" makes it pretty clear that ES6 module *syntax* works fine. – Felix Kling Nov 08 '19 at 12:16