我有一个节点应用程序,当我添加路由时:app.use('/api',routes),应用程序崩溃,没有这一行,应用程序就会运行。
错误为:返回db.collection(name)
^
TypeError:无法读取undefined的属性(读取“collection”)
因为db是未定义的。
索引:
import express from 'express'
import cors from 'cors'
import routes from './routes'
import { connectDB } from './db'
const port= process.env.port|| 5000
const app = express()
app.use(cors())
app.use(express.json())
app.use('/api', routes)
app.get('/', (req, res) => res.send('Running'))
connectDB().then(res => {
app.listen(port, () => console.log(`Running: http://localhost:${port}`))
}).catch(err => console.log(err))
db.ts:
let db: Db
export const connectDB = async (): Promise<void> => {
try {
const uri = process.env.MONGO_URI as string
const client = new MongoClient(uri)
await client.connect()
db = client.db(process.env.DB_NAME)
}catch(error) {
console.log(error)
}
}
export const getCollection = <T extends Document>(name: string): Collection<T> => {
return db.collection<T>(name)
}
'/routes/index.ts':
import { Router } from 'express'
import productRoutes from './products/productRoutes'
const router = Router()
router.use('/products', productRoutes )
export default router
productRoutes.ts:
import express from 'express'
import { createProduct } from '../../agents/product/productAgent';
router.post('/', async (req, res) => {
try {
const success = await createProduct(req.body);
res.status(success ? 201 : 400).json({ success });
} catch (error: any) {
res.status(500).json({ error: error.message });
}
})
产品代理:
import { getCollection } from '../../db'
import { ObjectId } from 'mongodb'
import { IProduct } from '../../types/IProduct'
const collectionProduct = getCollection<IProduct>('products')
export const createProduct = async (parameters: IProduct): Promise<boolean> => {
try {
const res= await collectionProduct.insertOne(parameters)
return res.acknowledged
} catch (error) {
throw new Error('Error create product')
}
}
我无法弄清楚出了什么问题,以及在主文件中添加“app.use('api',routes)”会如何影响我的数据库连接。