提问人:giuliana falconio 提问时间:10/23/2023 最后编辑:Lin Dugiuliana falconio 更新时间:10/27/2023 访问量:22
使用 node.js 连接到 Mongo 数据库时如何修复类型错误,我的代码是否正确?
How do i fix a typeError when using node.js to connect to Mongo db and is my code correct?
问:
我有一个名为 Exams 的数据库,在 Exams 里面有一个名为 Math_Exams 的文档,所以我试图将其存储在数组中,但我与数据库的连接不起作用,并且在终端中键入 node app.js(文件名)后出现此错误:
/Users/giulianafalconio/Desktop/Nueva carpeta/app.js:14
connectToDb().then(() => {
^
TypeError: Cannot read properties of undefined (reading 'then')
at Object.<anonymous> (/Users/giulianafalconio/Desktop/Nueva carpeta/app.js:14:14)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
at node:internal/main/run_main_module:23:47
this is the code I have:
应用.js:
const express = require('express')
const {connectToDb, getDb} = require('./examsdb')
const app = express()
let db
connectToDb(
(err) => {
if (!err) {
app.listen(3000, () => {
console.log('app listeing in port 3000')
})
db = getDb()
}
}
)
app.get('/Exams', (req, res) => {
let Math_Exams = []
db.collection('Math_Exams')
.find()
.toArray(Math_Exams => Math_Exams.push(Math_Exams))
.then(() => {
res.status(200).json(Math_Exams)
})
.catch(error => {
// catches errors
console.error(error)
res.status(500).json({error: 'Could not fetch the documents'}) // meaning server error
})
})
考试db.js:
const {MongoClient} = require('mongodb')
let dbConnection
module.exports = {
connectToDb: (cb) => {
MongoClient.connect('mongodb://localhost:27017/Exams')
.then((client) => {
dbConnection = client.db()
return cb()
})
.catch((err) => {
console.log(err)
return cb()
})
},
getDb: () => dbConnection,
}
应该在选项卡中显示如下:
但是Safari浏览器说他们无法连接到本地主机:
答: 暂无答案
评论