【问题标题】:how to solve TypeError: Cannot read property 'connect' of undefined in mongodb?如何解决TypeError:无法读取mongodb中未定义的属性'connect'?
【发布时间】:2021-05-17 10:55:42
【问题描述】:

我正在尝试在我的控制台中获取数据库

const mongoclient=require('mongodb').mongoclient

const state={
db:null
}

module.exports.connect=function(done){
      const url='mongodb://localhost:27017'
      const dbname='shopping'

           mongoclient.connect(url,(err,data)=>{
           if (err) return done (err)
           state.db=data.db(dbname)
           done()
})
}

           module.exports.get=function(){
           return state.db
}

并在下面出现以下错误

 project-e-commerce@0.0.0 start C:\Users\krish\Desktop\project e commerce
 > node ./bin/www

 C:\Users\krish\Desktop\project e commerce\config\connection.js:11
 mongoclient.connect(url,(err,data)=>{
            ^

 TypeError: Cannot read property 'connect' of undefined
 at Object.module.exports.connect (C:\Users\krish\Desktop\project e 
 commerce\config\connection.js:11:17)
 at Object.<anonymous> (C:\Users\krish\Desktop\project e commerce\app.js:24:4)

这是我在app.js 文件中的代码

db.connect((err)=>{
if (err) console.log("connection error"+err);
else console.log("database connected to port 27017");
})

【问题讨论】:

    标签: javascript node.js mongodb visual-studio-code typeerror


    【解决方案1】:

    报错说明你没有mongoclient。尝试先安装它。

    npm i mongodb --save
    

    一次,你就得到了 mongoclient。

    const MongoClient = require('mongodb').MongoClient;
    

    然后,尝试使用它连接 mongodb 实例:

    // Use connect method to connect to the server
    MongoClient.connect(url, (err, client) => {
      console.log("Connected successfully to server");
      const db = client.db(dbName);
      client.close();
    });
    

    【讨论】:

    • 谢谢!但它对我不起作用。仍然显示相同的错误
    • 你需要从 mongodb 获取 'MongoClient' 而不是 'mongoclient'。
    • 是的,在 fetch 之后。现在它显示新的错误
    • 你可以在这里添加什么?
    • (node:5620) 警告:在循环依赖和ReferenceError中访问模块导出的不存在属性“MongoError”:未定义dbName
    猜你喜欢
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2021-10-25
    • 2022-07-06
    • 1970-01-01
    • 2019-05-21
    相关资源
    最近更新 更多