【问题标题】:POSTing an array of objects to MongoDB in Node在 Node 中将对象数组发布到 MongoDB
【发布时间】:2016-04-02 05:26:46
【问题描述】:

我有一个从文本文件中解析出来的对象数组,我试图在前端使用 Node、Express、MongoDB 和 vanilla JS 和 JQuery 发送到我的数据库。

当我发布时,MongoDB 中显示的只是“_id”字段和“section”字段,后跟一个空数组。我想我的问题出在数据的结构上,我已经尝试了一些,但没有运气。

我的代码如下。任何帮助将不胜感激!

前端JS:

var openFile = function(event) {
    var input = event.target;
    var reader = new FileReader();
  reader.onload = function() {
    var text = reader.result;
    // console.log(text.substring(0, 999999999999999));
      var section = text.substring(0, 9999999999999999);
      var subSection = {};
      var masterArray = new Object();
      var uploadDate = "";
      var period = "";
      var transferArray = [];
      var allData = [];
      var subSectionRegex = /   Total([\s\S]*?)Total|^\s+\d{4,5}([\s\S]*?)Total F/gm;
      var transferCodeRegex = /[0-9]{4,5}/;
      var voucherNumberRegex = /([0-9]{7,10}[\S])(?=\s+)|\s\d{5}\w{1}(?=\s)/g;
      var vendorRegex = /(?!\d{10})(\S+\s\S+(\s\S+)?)(?=\s+100)|(?!\d{10})(\S+(\s\S+)?)(?=\s+100)/gm;
      var descriptionRegex = /(?!\d{10})(\S+\s\S+(\s\S+)?)(?=\s+100)|(?!\d{10})(\S+(\s\S+)?)(?=\s+100)|(?!\d{10})(\S+\s(\s\S+)?)(?=\s+100)/g;
      var amountRegex = /(?:\s\w{3}\s+|Capitation\s+)(\d+,\d+.\d+)(?=")|(?:\s\w{3}\s+|Capitation\s+)(\d+,\d+,\d+.\d+)(?=")|(?:\s\w{3}\s+|Capitation\s+)(-\d+,\d+.\d+)(?=")|(?:\s\w{3}\s+|Capitation\s+)(-\d+,\d+,\d+.\d+)(?=")/gm;
      var oneLineAmountRegex = /(\d+,\d+,\d+.\d+)|\d+,\d+.\d+/g;
      var oneLineDescRegex = / - (\D+)|- \d+(\D+)/gm;

        subSection = section.match(subSectionRegex);
        subSection = subSection.filter(Boolean);

      function extractDate() {
        uploadDate = section.match(/Date (.*)/)[1].trim();
        uploadDate = new Date(uploadDate);
        allData["uploadDate"] = uploadDate;
      }
      extractDate();
      // console.log(allData.uploadDate);

      function extractPeriod() {
        period = section.match(/Period (.*)/)[1].trim();
        period = period.split(" ");
        period = period[0];
        period = parseInt(period);
        // console.log("period: " + period);
        allData["period"] = period;
      }
      extractPeriod();
      // console.log(allData.period);

      function extractDetails() {
        for(var i = 0; i < subSection.length; i++) {
            if(subSection[i].match(transferCodeRegex) && subSection[i].match(voucherNumberRegex) && subSection[i].match(vendorRegex) && subSection[i].match(descriptionRegex) && subSection[i].match(amountRegex)) {
                transferArray.push({
                    "transferCode": subSection[i].match(transferCodeRegex),
                    "details": [{
                        "voucherNumber": subSection[i].match(voucherNumberRegex),
                        "vendor": subSection[i].match(vendorRegex),
                        "description": subSection[i].match(descriptionRegex),
                        "amount": subSection[i].match(amountRegex)
                    }]
                })
            } else {
                transferArray.push({
                    "transferCode": subSection[i].match(transferCodeRegex),
                    "details": [{
                        "voucherNumber": subSection[i].match(voucherNumberRegex),
                        "description": subSection[i].match(oneLineDescRegex),
                        "amount": subSection[i].match(oneLineAmountRegex)
                    }]
                })
            }
        }
        var clean = transferArray.map(function(transfer){
            transfer.details = transfer.details.map(function(detail){
                detail.amount = detail.amount.filter(function(quantity){
                if(quantity !== null){
                    return true;
                }
                });
                detail.amount = detail.amount.map(function(quantity){
                var num = quantity.replace(/[^-\d\.]+/g, '');
                    return Number(num);
                });
                return detail;
            });
            return transfer;
            });
      }
        //adds detailed data to allData array
      allData["section"] = transferArray;

      $.ajax({
        url: "http://localhost:3000/transfers/api",
        type: "POST",
        data: allData,
        datatype: 'json',
        success: function(data, textStatus, jqXHR) {
            alert('posted!')
        },
        error: function(data, textStatus, errorThrown) {
            alert('failed')
        }
      })
      extractDetails();
      console.log(allData);

      function sendDataToDB() {

      }
    }
  reader.readAsText(input.files[0]);
};

api模型:

var mongoose = require('mongoose');

var TransferSchema = new mongoose.Schema({
    uploadDate: Date,
    period: Number,
    IFMISFile: { type: mongoose.Schema.ObjectId, ref: 'ifmisFile' },
    section: [{
        transferCode: String,
        type: String,
        details: [{
            transferRecipient: String,
            voucherNumber: String,
            vendor: String,
            description: String,
            amount: Number
        }] 
    }] 
});

//convert schema to model
var Transfer = mongoose.model('Transfer', TransferSchema); 

//export model for use elsewhere in app
module.exports = Transfer;

api 控制器:

var Transfer = require('../models/Transfer');

//Get all transfers
function getAll(request, response) {
    Transfer.find(function(error, transfers) {
        if(error) response.json({message: 'couldn\'t find any transfers'});

        response.json({ transfers: transfers });
    }).select('-__v');
}

//Post a new transfer
function createTransfer(request, response) {
    console.log('posting');
    console.log('body: ' + request.body);

    var transfer = new Transfer(request.body);

    transfer.save(function(error) {
        if(error) response.json({ message: 'could not create transfer because ' + error });

        response.json({ transfer: transfer });
    });
}

//Delete
function removeTransfer(request, response) {
  var id = request.params.id;

  Transfer.remove({_id: id}, function(error) {
    if(error) response.json({message: 'Could not delete transfer b/c:' + error});

    response.json({message: 'Transfer successfully deleted'});
  }).select('-__v');
}

module.exports = {
    getAll: getAll,
    createTransfer: createTransfer,
    removeTransfer: removeTransfer
}

【问题讨论】:

  • 它在createTransfer 函数中显示什么,即console.log('posting');console.log('body: ' + request.body);
  • 嘿,抱歉耽搁了,我和家人不在家。 createTransfer 函数记录 [object Object]。在我的数据库中,我得到以下信息:{"_id": xxx, "section": [], "_v": xxx},而"section" 是空的,并且没有其他键(句点、日期)通过。
  • 我怀疑您从前端发送到后端的数据与您的传输架构不匹配。尝试通过console.log('body': + JSON.stringify(request.body)) 和transfer 对象检查request.body
  • 嗯,当我记录 JSON.stringify... 它返回 body: {}。我已经从前端记录了传输对象,它返回了应有的所有内容,日期格式与您记录时看到的一样 new Date(1/1/2016)
  • 尝试在 extractDetails();console.log(allData); 之后移动 $.ajax 调用,看看它是否有效

标签: jquery arrays ajax node.js mongodb


【解决方案1】:

transferArray 数组始终为空,因为您在发布之前 之后才运行extractDetails 函数!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-11
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2018-12-07
    相关资源
    最近更新 更多