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

MongoDB 6.0与Node.js连接报错:Unsupported OP_QUERY command: insert 求助

问题原因

你遇到的Unsupported OP_QUERY command: insert错误,本质是使用的MongoDB Node.js驱动版本过低——MongoDB 6.0已彻底移除老旧的OP_QUERY指令,而旧驱动仍依赖该指令执行写入操作,导致协议不兼容。

解决方案

1. 升级MongoDB Node.js驱动

执行命令升级到兼容MongoDB 6.0的最新稳定版驱动:

npm install mongodb@latest

也可指定最低兼容版本(v4.0及以上):

npm install mongodb@^4.0.0

2. 适配新版驱动API

新版驱动废弃了部分旧API(比如你代码里的result.ops),同时推荐用async/await简化代码逻辑,修改后的完整代码如下:

const { MongoClient } = require('mongodb');

const url = 'mongodb://localhost:27017';
const dbName = 'conFusion';

async function run() {
  let client;
  try {
    // 连接数据库
    client = await MongoClient.connect(url);
    console.log('Connected correctly to server');
    
    const db = client.db(dbName);
    const collection = db.collection('dishes');

    // 插入文档
    const insertResult = await collection.insertOne({name: "Uthapizza", description: "test"});
    console.log('Insert Document:', `插入ID: ${insertResult.insertedId}, 插入数量: ${insertResult.insertedCount}`);

    // 查询所有文档
    const docs = await collection.find({}).toArray();
    console.log('Found Documents:', docs);

    // 删除所有文档
    const deleteResult = await collection.deleteMany({});
    console.log('Deleted Documents:', `删除数量: ${deleteResult.deletedCount}`);
  } catch (err) {
    console.error(err);
  } finally {
    // 确保关闭连接
    if (client) {
      await client.close();
    }
  }
}

run();

关键API变更说明

  • 移除result.ops:新版插入操作返回对象用insertedId(单条插入)/insertedIds(批量插入)获取ID,insertedCount获取插入数量
  • 推荐用async/await替代链式then,代码逻辑更直观
  • 新版MongoClient.connect直接通过await获取客户端对象,无需在回调中接收

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 21:50:23