从猫鼬节点js中的不同模型获取数据

时间:2020-02-11 10:10:12

标签: node.js mongodb mongoose

我有两个模型文件,银行存款和子帐户详细信息。我想从子帐户详细信息中获取current balance到银行存款。我想在mongodb和node js中执行此操作。我目前正在进行查找操作,但该数组显示为空。

BankdepositModel.js

var mongoose = require("mongoose");

var BankDepositsSchema = new mongoose.Schema(
  {
    source_sub_account: Array,
    amount: Number,
    cheque_notes: Number,
    to_bank_account: Array,
    amount_in_words: String,
    bank_Ref_no: String
  },
  {
    timestamps: true
  }
);

module.exports = mongoose.model("BankDeposits", BankDepositsSchema);

Subaccountdetailsmodel.js

var mongoose = require("mongoose");

var SubAccountDetailsSchema = new mongoose.Schema(
  {
    sub_account_name: String,
    current_balance: Number,
    account: Array
  },
  {
    timestamps: true
  }
);

module.exports = mongoose.model("SubAccountDetails", SubAccountDetailsSchema);

Controller.js

var BankDeposits = require("../model/bankdepositmodel");
var SubAccountDetails = require("../model/subaccountsmodel.js");

exports.create1 = (req, res) => {
  var BankDeposit = new BankDeposits({
    source_sub_account: req.body.source_sub_account,
    amount: req.body.amount,
    cheque_notes: req.body.cheque_notes,
    to_bank_account: req.body.to_bank_account,
    amount_in_words: req.body.amount_in_words,
    bank_ref_no: req.body.bank_ref_no
  });

  BankDeposit.save()
    .then(data1 => {
      res.send(data1);
    })
    .catch(err => {
      res.status(500).send({
        message: err.message
      });
    });
};

//BankDeposit get
exports.find1 = (req, res) => {
  BankDeposits.aggregate([
    {
      $lookup: {
        from: "SubAccountDetails",
        localField: "current_balance",
        foreignField: "current_balance",
        as: "balance"
      }
    }
  ])
    .then(appdata => {
      res.status(200).send(appdata); //On successful fetch, server responds with status 200
    })
    .catch(err => {
      res.status(400).send(err); //On error, server responds with status 400
    });
};
//sub account details post
exports.createSubAccountDetail = (req, res) => {
  var SubAccountDetail = new SubAccountDetails({
    sub_account_name: req.body.sub_account_name,
    current_balance: req.body.current_balance,
    account: req.body.account
  });

  SubAccountDetail.save()
    .then(SubAccountDetail => {
      res.send(SubAccountDetail);
    })
    .catch(err => {
      res.status(500).send({
        message: err.message
      });
    });
};

//sub account details get
exports.SubAccountDetail = (req, res) => {
  SubAccountDetails.find()
    .then(SubAccountDetails => {
      res.send(SubAccountDetails);
    })
    .catch(err => {
      res.status(500).send({
        message: err.message || "Some error occurred while retrieving regs."
      });
    });
};

0 个答案:

没有答案