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

NodeJS Mongoose事务场景调用Schema实例方法报is not a function错误

问题根因

你调用Customer.create时第一个参数传入了数组[{ firstName: "john" }],根据Mongoose的API规则,只要create方法接收的第一个参数是数组类型,无论是否开启事务,返回值都是文档实例组成的数组,而非单个文档实例。你打印的customer内容也能印证这一点,数据外层有数组包裹。
你直接对数组调用仅Customer实例才有的hello方法,自然会触发not a function的类型错误。

你提到非事务场景可以正常调用,是因为非事务场景下你大概率用了常规写法,给create传的第一个参数是单个对象而非数组,此时返回的是单个Customer实例,可以正常调用实例方法:

// 非事务场景常见写法,返回单个实例
const customer = await Customer.create({ firstName: "john" });

解决方案

两种修改方式二选一即可:

  • 如果你确实需要批量创建文档,create第一个参数保留数组格式,取数组的第一个元素调用实例方法即可:
    const customers = await Customer.create([{ firstName: "john" }], { session: session });
    const customer = customers[0];
    customer.hello();
    
  • 如果仅创建单个文档,create第一个参数直接传对象,不需要包裹数组,事务场景下也支持直接传session选项:
    const customer = await Customer.create({ firstName: "john" }, { session: session });
    customer.hello();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 00:45:05