【问题标题】:MongoDB & Mongoose, Save Nested Array of Objects - Node.jsMongoDB 和 Mongoose,保存嵌套的对象数组 - Node.js
【发布时间】:2021-08-13 21:53:24
【问题描述】:

我正在尝试将嵌套的对象数组保存到我的 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;

【问题讨论】:

    标签: node.js mongodb mongoose backend mongoose-schema


    【解决方案1】:

    您可以尝试像这样重构您的.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");
        }
      })
    

    【讨论】:

    • 欢迎。如果对您有帮助,也请考虑支持我的回答。
    猜你喜欢
    • 2017-06-26
    • 2019-09-11
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2014-11-09
    • 2023-01-18
    • 2014-10-16
    相关资源
    最近更新 更多