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

咨询:为何此处insert不是函数?附报错信息及代码

嘿,这个报错我太熟悉啦!你遇到的db.collection(...).insert is not a function问题,其实是MongoDB Node.js驱动版本更新带来的API变化导致的,我来给你拆解一下:

为什么会出现这个报错?

你当前使用的应该是MongoDB Node.js驱动4.x及以上版本,在这些新版本里,官方已经弃用并移除了旧的insert()方法,转而提供了语义更明确的insertOne()(用于插入单条文档)和insertMany()(用于插入多条文档)方法。而在3.x及更早的旧版本驱动中,insert()是可以正常使用的,这就是新旧版本API的差异点。

怎么解决?

你的代码是要插入单条商家数据,只需要把insert替换成insertOne就可以修复这个问题了,修改后的代码如下:

function addBusiness() { 
  db.collection("businesses").insertOne({
    owner_id : client.authedId(), 
    city: "mycity", 
    county: "mycounty", 
    name: "mybusiness", 
    state: "myState", 
    street: "mystreet", 
    zip: "myzip"
  }); 
}
额外小提示

如果你之后需要插入多条文档,记得用insertMany(),传入一个文档数组就行。另外要注意,insertOne()和insertMany()都是异步方法,要是你需要处理插入成功后的结果或者捕获错误,建议用async/await或者Promise回调来处理,比如:

async function addBusiness() { 
  try {
    const insertResult = await db.collection("businesses").insertOne({
      owner_id : client.authedId(), 
      city: "mycity", 
      county: "mycounty", 
      name: "mybusiness", 
      state: "myState", 
      street: "mystreet", 
      zip: "myzip"
    });
    console.log(`文档插入成功,ID是:${insertResult.insertedId}`);
  } catch (error) {
    console.error("插入操作失败:", error);
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:40:33