i'm beginner of typescript.
when i 'npm run dev', it successfully connect to the server (localhost:5000)
but mongoose.connect is not working.
i move this db/index.ts to server.ts
--> it working and terminal shows server connect okay, mongo connet also okay.
but that mongoose connect code in db/index.ts is not working...
what's the problem?? can i modify npm scripts??
package.json
"scripts": {
"start": "nodemon --watch '*.ts' --signal SIGTERM --exec ts-node server.ts",
"build": "tsc -p .",
"dev": "nodemon --watch \"src/**/*.ts\" --exec \"ts-node\" server.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@tsconfig/node16-strictest-esm": "^1.0.3",
"@types/cors": "^2.8.12",
"@types/express": "^4.17.14",
"@types/mongoose": "^5.11.97",
"@types/node": "^18.7.19",
"@typescript-eslint/eslint-plugin": "^5.38.0",
"@typescript-eslint/parser": "^5.38.0",
"eslint": "^8.24.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.31.8",
"nodemon": "^2.0.20",
"prettier": "^2.7.1",
"ts-node": "^10.9.1",
"tsc-watch": "^5.0.3",
"typescript": "^4.8.3"
},
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^16.0.2",
"express": "^4.18.1",
"mongoose": "^6.6.1"
}
tsconfig.json
{
"extends": "@tsconfig/node16/tsconfig.json",
"include": ["src/**/*", "bin/*"],
"exclude": ["node_modules", "**/*.spec.ts"],
"compilerOptions": {
"rootDir": ".",
"outDir": "dist",
"typeRoots": ["node_modules/@types", "src/@types"]
},
"ts-node": {
"files": true
}
}
server.ts
import 'dotenv/config';
import { app } from './src/app';
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Successfully CONNECT. http://localhost:${PORT}`);
});
db/index.ts
import mongoose from 'mongoose';
const DB_URL =
process.env.MONGODB_URL ||
'MongoDB address is not set.\n check ./db/index.ts \n need .env \n';
mongoose.connect(DB_URL);
const db = mongoose.connection;
db.on('connected', () => console.log('connect success!!' DB_URL));
db.on('error', (error) =>
console.error('\n connect fail...\n' DB_URL '\n' error),
);
CodePudding user response:
Have you imported db/index.ts into your app.ts? if not then do import
Or/
You've not imported db/index.ts to your server.ts file.
That's why mongodb is not being connected.
what you've to do is "Just import db/index.tx in your server.ts"