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

新手求助:TypeError: User.insertMany is not a function报错解决

问题:TypeError: User.insertMany is not a function

我的代码:

import express from 'express';
import User from './Models/UserModel.js';
import users from './data/users.js';

const ImportData = express.Router();

ImportData.post('/user', async (req, res) => {
  await User.remove({});
  const importUser = await User.insertMany(users);
  res.send({ importUser });
});

export default ImportData;

运行时出现错误:

const importUser = await User.insertMany(users);
                                ^  

TypeError: User.insertMany is not a function

我是编程新手,不知道该如何修复这个问题,希望得到帮助。


解答

这个错误的核心原因是你导入的User不是合法的Mongoose模型实例,导致它没有insertMany这个内置方法,按以下步骤排查修复:

  • 检查UserModel.js的导出逻辑
    确保你的UserModel.js正确创建并导出Mongoose模型,示例代码如下:

    import mongoose from 'mongoose';
    
    // 定义用户Schema
    const userSchema = new mongoose.Schema({
      name: { type: String, required: true },
      email: { type: String, required: true, unique: true },
      // 按需添加其他字段
    });
    
    // 创建并导出模型
    const User = mongoose.model('User', userSchema);
    export default User;
    

    如果你的UserModel.js只导出了Schema对象,没有通过mongoose.model()生成模型,就会触发这个错误。

  • 替换过时的remove方法
    顺带提一句,User.remove({})是Mongoose的过时方法,现在推荐用User.deleteMany({})删除所有文档,避免后续版本兼容性问题。

  • 确认Mongoose版本
    若你使用的是非常老旧的Mongoose版本,可能存在方法缺失的情况,建议运行npm install mongoose@latest升级到稳定版。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:04:59