MongoDB & Mongoose,保存对象的嵌套数组 - Node.js

MongoDB & Mongoose, Save Nested Array of Objects - Node.js

我正在尝试将嵌套的对象数组保存到我的 MongoDB 集合中,但该应用程序仅将第一个对象保存在嵌套的 BankAccountsArray 中,我尝试使用 .markModified() 方法但是没有取得任何成功。我附上了从前端部分接受的数据+我的模型架构+路线,感谢您的帮助!

已接受前端数据:

 {
      companyHoldingPercentage: '10%',
      BankAccountsArray: [
        {
          bankAccountNumber: '32',
          bankBranchNumber: '55',
          bankName: 'abc'
        },
        {
          bankAccountNumber: '3123',
          bankBranchNumber: '412',
          bankName: 'cde'
        }
      ]
    }

型号:

const mongoose = require("mongoose");

const BankAccountsArraySchema = mongoose.Schema({
  bankName: String ,
  bankBranchNumber: String ,
  bankAccountNumber: String
}
);

const BankAccountsIndexSchema = mongoose.Schema({
  companyHoldingPercentage: String ,
  BankAccountsArray: [BankAccountsArraySchema]

});
module.exports = mongoose.model(
  "bank-accounts-object",
  BankAccountsIndexSchema
);

路线:

var express = require("express");
var router = express.Router();
const BankAccountsIndexModel = require("../Models/BankAccountsIndexModel");
router
  .route("/BankAccountsIndexRoute")
  .get(async (req, res, next) => {
    BankAccountsIndexModel.find((err, collection) => {
      if (err) {
        console.log(err);
      } else {
        res.json(collection); 
      }
    });
  })
  .post(async (req, res, next) => {
    console.log(req.body);

    const {
      companyHoldingPercentage,
      BankAccountsArray: [{ bankName, bankBranchNumber, bankAccountNumber }],
    } = req.body;

    try {
      const NewBankAccountsIndexModel = new BankAccountsIndexModel({
        companyHoldingPercentage,
        BankAccountsArray: [{ bankName, bankBranchNumber, bankAccountNumber }],
      });

       NewBankAccountsIndexModel.markModified(req.body.BankAccountsArray);

       NewBankAccountsIndexModel.save();
      // res.json(bankAccount);
    } catch (err) {
      console.error(err.message);
      res.status(500).send("Server error");
    }
  })

module.exports = router;

你能尝试像这样重构你的 .post() 端点吗:

.post(async (req, res, next) => {
    try {
      let new_bank_account = await BankAccountsIndexModel.create(req.body);
      res.status(200).json(new_bank_account);
    } catch (err) {
      console.error(err.message);
      res.status(500).send("Server error");
    }
  })