0

I'm very new to node and mongoose schemas, so this might be a noob question.

I'm trying to fetch the data to display on my home page. Right now, the home page uses a function in a separate file to call the Api and fetch from the backend, which seems to be working. On the backend of my route, I make two calls to separate DB functions. One that adds the payment to the payment collection and the other that updates the values in the user details collection.

When I make my db calls, it seems to get hung up and cannot complete the query. I tested this by just logging to the console and the log before the function prints, but the one after does not.

This is my router code:

const express = require('express');
const db = require('../db/DbCalls');
const historyRoutes = express.Router();

// will collect/sort by date all purchases, refunds, and payments for user
historyRoutes.route("/home").get( async function (req, res) {
    let transactions = [];
    const params = {
        limit: 0
    }
    //retrieve lists
    const purchases =  await db.getPurchases(params);
    const payments =  await db.getPayments();
    const refunds =  await db.getRefunds();
    //merge lists
    transactions = purchases.concat(payments);
    transactions = transactions.concat(refunds);
    //sort lists by most recent transaction
    transactions.sort(function(a,b){
        return a.date - b.date;
    });
    res.json(transactions);
});
module.exports = historyRoutes;

These are my database call functions

const Purchase = require('../Schemas/purchase');
const Payment = require('../Schemas/payment');
const Refund = require('../Schemas/refund');
const User = require('../Schemas/user');
// All database functions used in router files
    // retrieves all purchases
    async function getPurchases(params) {
        try {
            console.log(params.limit);
            console.log('entered');
            Purchase.find().limit(params.limit).exec(
                function (err, results ){
                    if (err) console.log('error');
                    console.log(results);
                    return results;
                }
            );
        } catch (err) {
            console.log('error');
            throw (err);
        }
    }
    // retrieves all payments
    async function getPayments() {
        try {
            const results = await Payment.find().exec();
            console.log(results);
            return results;
        } catch (err) {
            console.log(err);
            throw err;
        }
    }
    // retrieves all refunds
    async function getRefunds() {
        try {
            const results = await Refund.find().exec();
            console.log(results);
            return results;
        } catch (err) {
            console.log(err);
            throw err;
        }

    }
    // retrieves max limit, current limit, and current balance
    async function getUserDetails() {
        try{
            const results = await User.findOne({name: 'user'}).exec();
            console.log(results);
            return results;
        }catch (err) {
            console.log(err);
            throw err;
        }
    }
    // updates user details
    async function updateUserDetails(body) {
        try {
            const result = await User.updateOne({name:'user'},body).exec();
            console.log(result);
            return result;
        } catch (err) {
            console.log(err);
            throw err;
        }
    }
    // adds a single transaction

    async function addPayment(body){
        const payment = new Payment({
            transType: 'payment',
            amount:body.amount,
            title: 'Paid to Fizz',
            count: body.count,
            date: Date.now()
        });
        thing.save().then(
            ()=> {
                console.log('Added Payment Successfully');
                return
            }
        ).catch(
            (err)=> {
                console.log(`Error adding payment ${err}.`);
                return
            }
        )
    }
    async function addTransaction(body) {
        try {
            let result;
            if (body.type === 'purchase') {
                result = await Purchase.insertOne(body);
            }
            if (body.type === 'payment') {
                result = await Payment.insertOne(body);
            }
            if (body.type === 'refund') {
                result = await Refund.insertOne(body);
            }
            console.log(result);
            return result;
        } catch (err) {
            throw err;
        }
    }
module.exports = {addTransaction, updateUserDetails, getPayments, getPurchases, getRefunds, getUserDetails};

These are my schemas

const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const paymentSchema = new Schema({
    transType: {type: String, required:true},
    amount: {type: Number, required:true},
    title: {type: String, required:true},
    rfndStatus : {type: Boolean, required:true},
    count : {type: Number, required:true},
    date: {type: Date, required:true}
});

module.exports = mongoose.model("payment", paymentSchema);
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
const purchaseSchema = new Schema({
    transType: {type: String,required:true},
    amount: {type: Number,required:true},
    title: {type: String,required:true},
    rfndStatus : {type: Boolean,required:true},
    date: {type: Date,required:true}
});

module.exports = mongoose.model('purchase', purchaseSchema);
const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const refundSchema = new Schema({
    transType: {type: String, required:true},
    title: {type: String, required:true},
    amount: {type: Number, required:true},
    date: {type: Date, required:true}
});

module.exports = mongoose.model("refund", refundSchema);
const mongoose = require('mongoose');
var Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {type:String},
    balance: {type: Number, required: true},
    currentLimit: {type:Number, required: true},
    MaximumLimit: {type: Number, required: true}
});

module.exports = mongoose.model("user", userSchema);

I don't really know where I'm going wrong in structure.

Ken White
  • 123,280
  • 14
  • 225
  • 444
  • I don't see where the code calls the functions which insert and update into the db. Am I missing something? – Michael Ruth Dec 09 '22 at 01:15
  • @MichaelRuth I'm using the schema models to directly interact with the database. In the database functions portion you can see in the try block where I call Purchase.find(). I figured this should call the database using my Purchase Schema. – justin.cote Dec 09 '22 at 01:31
  • Those are just function _definitions_, they need to be called somewhere in the code in order to be executed; unless there's some framework magic going on that I'm unaware of. – Michael Ruth Dec 09 '22 at 01:40
  • @MichaelRuth I was referencing this document when making those. I export these functions to the routing page and call them there. I use '''const db = require('../db/DbCalls');''' to import them and use through the document as db.(). What exactly should I change to get a successful result? Thanks. – justin.cote Dec 09 '22 at 01:50
  • Yes, but where are they _called_? Exporting, and then importing in the router doesn't call them, it just defines them in the router's namespace. The only db functions I see called in the router are getXXX(). – Michael Ruth Dec 09 '22 at 01:52
  • @MichaelRuth I'm confused... are those db.getXXXX() not the same as those in the db call file? I want to use those functions in the routing function. – justin.cote Dec 09 '22 at 02:02
  • also it says that those functions are being executed because the console.log('entered') line is executed when I refresh the frontend page and then just gets hung up in the api call. – justin.cote Dec 09 '22 at 02:03
  • From the context, I think you are asking about an issue with the updates and inserts. The code provided only calls db functions which fetch. – Michael Ruth Dec 09 '22 at 02:04
  • Assuming the issue is with the db.getXXX()s: why does the code call `exec()` on the returned value of the `find()`? – Michael Ruth Dec 09 '22 at 02:09
  • @MichaelRuth the function pertaining to this issue is the get. I'm trying to read documents from the database with the functions (getPurchases, getPayments, getRefunds). In efforts to clean it up I made all those separate functions because they all go to different collections. The routing file should then call each of these functions to build a list of documents to return back to the frontend. – justin.cote Dec 09 '22 at 02:10
  • I've never worked in these languages before so I was just playing around with exec to see if that would solve anything. I just want to call those functions to return a list of the documents to then concatenate and return to the front end for display. – justin.cote Dec 09 '22 at 02:12
  • Cool, I get it now. This is why a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) is required by SO, it helps avoid confusion. Please produce such an example with seed data for the database. Other than the `exec()` issue, I can't think of any reason these queries would fail to complete except for a db config issue. – Michael Ruth Dec 09 '22 at 02:13
  • Gotcha, you don't need `exec()` to execute a `find()`, it executes on its own. Try removing the `exec()`s. – Michael Ruth Dec 09 '22 at 02:13

0 Answers0