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

Node.js使用Mongoose调用insertOne插入数据时报TypeError问题求助

问题原因
  • Mongoose 模型本身没有insertOne方法。insertOne是原生MongoDB Node.js驱动的集合方法,Mongoose封装后对应的单条文档插入方法是create。如果确实要调用原生驱动的方法需要先通过ServicesModel.collection访问原生集合对象再调用insertOne,但该写法会跳过Mongoose的schema校验、预操作中间件等逻辑,不推荐使用。
  • 定义的Schema字段和实际插入的字段不匹配:Schema中声明的必填字段是cnum、location、name,但你传入的文档里只有cnum匹配,location对应的是你传的siteLocation,name对应你传的Services,还多了Schema未定义的date字段,默认Mongoose会自动过滤未在Schema中声明的字段,且缺少必填字段会触发校验错误。
  • 插入操作是异步操作,你当前的代码没有等待插入完成就直接返回响应,会出现前端收到成功响应但实际数据库插入失败的情况。
修正方案

首先调整路由代码,适配Mongoose的操作规则:

const ServicesModel = require('../model/services')
// 改为async函数支持await异步等待
app.post('/updateServices', async (req, res) => {
    // 从请求中获取参数
    const { siteLocation, Services: name, date, cnum } = req.body;
    console.log(siteLocation, name, date, cnum)
    try {
        // 构造符合Schema要求的文档
        const doc = {
            cnum,
            location: siteLocation,
            name: name
            // 如果需要保留date字段,需要先在Schema中添加date字段定义
        };
        // 调用Mongoose的create方法插入单条数据
        await ServicesModel.create(doc);
        res.status(200).send("success")
    } catch (err) {
        // 捕获错误,比如字段校验失败、cnum重复等问题
        console.error('插入失败:', err);
        res.status(500).send("插入失败:" + err.message)
    }
})

如果需要保留date字段,需要在Schema中添加对应配置:

const servicesSchema = new mongoose.Schema({
    cnum: {
        type: String,
        required: true,
        unique: true,
        trim: true
    },
    location: {
        type: String,
        required: true,
        trim: true
    },
    name: {
        type: String,
        required: true,
        trim: true
    },
    // 新增date字段
    date: {
        type: Date,
        required: true
    }
}, {
    timestamps: true
})

补充说明:你的接口命名为updateServices,如果实际需求是更新已存在的cnum对应服务数据,而非插入新数据,应该使用更新类方法,示例:

await ServicesModel.findOneAndUpdate({cnum}, doc, {new: true})

更贴合接口的语义。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 01:36:01