You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MongoClient连接MongoDB时触发TypeError错误求助

解决MongoClient连接MongoDB时的TypeError问题

你遇到的TypeError: Cannot read properties of undefined (reading 'connect')错误,根源是代码里的拼写错误:你把MongoClient拼写成了MnogoClient,导致导入的成员不存在,MnogoClient为undefined,调用其connect方法自然报错。

修正要点:

  • 修正导入语句里的拼写错误,将MnogoClient改为MongoClient
  • 若使用MongoDB驱动4.x及以上版本,ObjectID需改为ObjectId(小写d);同时result.ops已被弃用,推荐用result.insertedId获取插入文档的ID

修正后的完整代码:

const { MongoClient, ObjectId } = require('mongodb')
const id = new ObjectId()
console.log(id)

const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'

MongoClient.connect(connectionURL, { useNewUrlParser: true }, (error, client) => {
    if (error) {
        return console.log(error)
    }

    const db = client.db(databaseName)

    db.collection('users').insertOne({
        _id: id,
        name: 'Mahdi',
        age: 24
    }, (error, result) => {
        if (error) {
            return console.log('Unable to insert the document')
        }
        console.log(result.insertedId) // 替代原result.ops,更符合新版驱动规范
    })
})

内容的提问来源于stack exchange,提问作者mahdi monfared

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 15:39:36