$ npm start
server@1.0.0 start nodemon index.js
[nodemon] 2.0.19 [nodemon] to restart at any time, enter rs
[nodemon] watching path(s): . [nodemon] watching extensions: js,mjs,JSON [nodemon] starting node index.js
D:\React\authInMern\server\index.js:8 connection(); ^
TypeError: connection is not a function at Object. (D:\React\authInMern\server\index.js:8:1) at Module._compile (node:internal/modules/cjs/loader:1126:14) at Object.Module._extensions..js (node:inter enter code here
nal/modules/cjs/loader:1180:10) at Module.load (node:internal/modules/cjs/loader:1004:32) at Function.Module._load (node:internal/modules/cjs/loader:839:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47 [nodemon] app crashed - waiting for file changes before starting...
index.js
require('dotenv').config();
const express = require("express");
const app = express();
const cors = require("cors");
const { connection } = require("./db");
// database connection
connection();
// Middlewares
app.use(express.json())
app.use(cors());
const port = process.env.PORT || 8080;`enter code here`
app.listen(port, () => console.log(`Listening on port $(port)...`));
db.js
const mongoose = require("mongoose");
module.exports = () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
try {
mongoose.connect(process.env.DB, connectionParams);
console.log("Connected to database successfully")
} catch (error) {
console.log(error);
console.log("could not connect to database");
}
};
Do it this way, if you want the connection function to be destructured
const mongoose = require("mongoose");
const connection = () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
try {
mongoose.connect(process.env.DB, connectionParams);
console.log("Connected to database successfully")
} catch (error) {
console.log(error);
console.log("could not connect to database");
}
};
module.exports = { connection }
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.