Search code examples
node.jsmongodbmongoosebackendmongoose-schema

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


I'm trying to save a nested array of objects to my MongoDB collection but the app is only saving the first object in the nested BankAccountsArray, I've tried using the .markModified() method but haven't got any success. I've attached the data accepted from the frontend part + my model schema + the route, Thanks for the help!

Frontend Data Accepted:

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

Model:

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
);

Route:

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;

Solution

  • Can you try to refactor your .post() endpoint like this:

    .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");
        }
      })