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

使用Mongoose和Node.js时含数组的文档无法插入MongoDB求助

数据库插入失败排查求助

@Norman,感谢您的回复。我正努力排查数据插入失败的问题,以下是我的代码和尝试过程:

引入依赖与初始化

const { body, validationResult } = require("express-validator");
const Customer = require('../models/custdetails');
const async    = require('async');

创建Customer对象

我先编写了数据清理代码,接着创建了customer对象(其中firm_feature和cust_need是数组类型字段):

const customer = new Customer({
  firm_name : req.body.firm_name,
  firm_feature : req.body.firm_feature,
  first_name: req.body.first_name,
  last_name: req.body.last_name,
  mob_no: req.body.mob_no,
  cust_email : req.body.cust_email,
  date_of_onboard: req.body.date_of_onboard,
  date_of_visit: req.body.date_of_visit,
  cust_need : req.body.cust_need,
  status : req.body.status,
  contact_back : req.body.contact_back,
});

第一次尝试的插入代码

const data = req.body;
customer.update({$push: {customer: data},function(err, res){if (err) {
          console.log("This is the error while inserting data:", err);
          }else {console.log(res); }   }   });

          res.redirect(customer.url);
        }
]

这次数据没能成功插入数据库,我又尝试了另一种写法:

第二次尝试的插入代码

(async function(){
          try {
            const filter = { first_name: req.body.first_name};
            const options = {upsert: true};  
            const result = await customer.updateOne(filter, {$set:{data}}, options).then(function(){
            console.log("data is inserted");
            console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`)
          })
           }catch(err) {
            console.log("Some error has occurred in insertion");
            console.log(err);
          };
        });
        res.status(200).redirect(customer.url);
      }

模型文件custdetails.js内容

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const CustSchema = new Schema(
  {
    firm_name:{type: String, maxLength:50},
    firm_feature: {type : { type: String }, enum: ['Private Limited Company', 'Public Limited Company',
                                      'Partnerships Company', 'Limited Liability Partnership LLP',
                                      'One Person Company', 'Sole Proprietorship',
                                      'Section 8 Company']},
    first_name: {type: String, required: true, maxLength: 100},
    last_name: {type: String, required: true, maxLength: 100},
    mob_no: {type: Number, required: true, maxLength:10},
    cust_email:{type: String, lowercase: true}, //always converts emailto lowercase before saving
    date_of_onboard: {type: Date},
    date_of_visit: {type: Date},
    cust_need: {type : { type: String }, enum:['Four Wheeler Loan', 'Home Loan', 'Two Wheeler Loan']},
    brperson: {type: Schema.Types.ObjectId, ref: 'Branch'},
    status: {type: Schema.Types.ObjectId, ref: 'CustInstance'},
    contact_back: {type: Schema.Types.ObjectId, ref: 'CustInstance' },

  }
);

//Export model
module.exports = mongoose.model('Customer', CustSchema);

我尝试了多种方法仍未解决问题,恳请帮助排查。


问题分析与解决方案

  1. 模型字段定义错误:你提到firm_feature和cust_need是数组类型,但模型里的写法有误,正确的数组类型定义应该是:
firm_feature: {type: [String], enum: ['Private Limited Company', 'Public Limited Company',
                                  'Partnerships Company', 'Limited Liability Partnership LLP',
                                  'One Person Company', 'Sole Proprietorship',
                                  'Section 8 Company']},
cust_need: {type: [String], enum:['Four Wheeler Loan', 'Home Loan', 'Two Wheeler Loan']}
  1. 插入方式错误:

    • 第一次使用customer.update()是错误的,你已经创建了customer实例,插入新文档应该用实例的save()方法:
      try {
        await customer.save();
        res.redirect(customer.url);
      } catch (err) {
        console.log("插入失败:", err);
      }
      
    • 第二次的updateOne调用对象错误,应该用模型Customer而非实例,且自执行函数未调用,同时{$set:{data}}会将data作为单个字段存入,正确写法如下:
      (async function(){
        try {
          const filter = { first_name: req.body.first_name};
          const options = {upsert: true};  
          const result = await Customer.updateOne(filter, {$set: req.body}, options);
          console.log("data is inserted");
          console.log(`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`);
          res.status(200).redirect(customer.url);
        } catch(err) {
          console.log("插入出错:", err);
        };
      })(); // 必须加()执行自执行函数
      
  2. 其他注意事项:

    • mob_no定义为Number类型可能丢失前导零,建议改为String类型;
    • 插入前需验证请求数据是否符合模型规则,可通过express-validator的校验结果判断:
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
      }
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:30:49