我是打字的初学者。
当i 'npm run dev'时,它成功连接到服务器(localhost:5000)
但是mongoose.connect不起作用。
我将此数据库/index.ts移动到server.ts
--〉工作正常,终端显示服务器连接正常,mongo连接也正常。
但是db/index.ts中mongoose连接代码无法正常工作...
有什么问题吗?我可以修改npm脚本吗?
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}`);
});
数据库/索引.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),
);
这是我的终端x1c 0d1x
1条答案
按热度按时间332nm8kg1#
您是否已将db/index.ts导入到您的app.ts中?如果没有,请执行导入
或/
您尚未将db/index.ts导入到服务器的.ts文件中。
这就是为什么mongodb没有被连接。
你要做的就是“把db/index.tx导入你的server.ts”