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

Node.js中Mongoose连接MongoDB无响应及数据存储问题解决

Mongoose与MongoDB连接及数据插入问题解决

环境信息

  • 操作系统:Windows 10
  • 编辑器:VS Code 1.74.2
  • Node.js版本:18.12.1
  • MongoDB版本:4.13
  • Mongoose版本:从5.0.1升级至5.13.15

问题过程与错误

  1. Mongoose v5.0.1连接成功但无法插入数据
    使用以下代码能正常输出Connected...:

    const mongoose = require('mongoose')
    
    mongoose.connect('mongodb://localhost/playground')
        .then(() => console.log('Connected...'))
        .catch(err => console.error('Could not connect...', err))
    

    但调用.save()插入JSON对象时,抛出错误:

    errmsg: 'Unsupported OP_QUERY command: insert. The client driver may require an upgrade.',
      code: 352,
      codeName: 'UnsupportedOpQueryCommand'
    
  2. 升级Mongoose后连接失败
    将Mongoose升级到5.13.15后,原代码出现弃用警告:

    (node:10772) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
    (Use `node --trace-deprecation ...` to show where the warning was created)
    (node:10772) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
    

    同时报错连接失败:

    MongoNetworkError: failed to connect to server [localhost:27017] on first connect
    
  3. 添加连接选项后超时无输出
    按照警告提示添加选项后,代码如下,但连接超时无任何输出:

    mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
        .then(() => console.log('Connected...'))
        .catch(err => console.error('Could not connect...', err))
    

解决方法

将连接URL替换为mongodb://127.0.0.1:27017/playground,即可正常连接并插入数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:46:03