S
S
Shakir Darion2019-11-08 15:16:56
Mongoose
Shakir Darion, 2019-11-08 15:16:56

TypeError: mongoose.connect is not a function?

when i use require commonjs everything works

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

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

but when i use ES6 import i get error
import { connect } from "mongoose";

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

SyntaxError: Requested module > 'file: node_modules/mongoose/index > .js' does not provide an export named 'connect'
and if you write like this
import * as mongoose from "mongoose";

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

TypeError: mongoose.connect is not a
package.json function
{
  "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 es6 module. Is there a way to use es6 modules with mongoose without getting an error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Magnus Keef, 2020-08-04
@SecurityYourFingers

I faced the same issue.
If you are using mongoose in a browser environment like me. I use react and in one of the components I tried to do mongoose.connect ()
In this case, the mongoose object will not have a connect method.
It is necessary to move the connection code into a separate file that will be executed in the nodejs environment.
Then mongoose will have the connect method and everything will work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question