David Pallett
David Pallett

Reputation: 1

NodeJS with Express and Mongoose trying to call one piece of middleware from another

I am trying to reuse code I have in two different NodeJS controllers but I seem to have not understood how the java calls work. The data comes from a MongoDB using Mongoose

I can call the picture code - findMyBoatPictures fine on its own but when I try to do so from the boat controller code - findMyForSale my trace is

trace produces this from NodeJS

 in boats findMyBoatPictures
 picture found records: 3

So the 3 records are found but after that it disappears somewhere and I cant see where

Any help would be greatly appreciated

What I am trying to achieve is that after having got the three records I want to add part of each record to the first of my boat records which were returned in the Boat.find and then repeat this process for each boat record

picture.routes.js

module.exports = function(app) {
    const picture = require('../controllers/picture.controller.js');
    // Retrieve all by boat Id
    app.get('/api/pictures/:boatId', picture.findMyBoatPictures);
}

boat.routes.js

module.exports = function(app) {
    const boats = require('../controllers/boat.controller.js');
    // Retrieve all Boats for sale
    app.get('/api/boatsforsale/:agentId', boats.findMyForSale);
}

boat.controller.js

const Boat = require('../models/boat.model.js');
const picture = require('../controllers/picture.controller.js');

// FETCH all Boats for sale by specified agent
exports.findMyForSale = (req, res) => {
    var query = { sellingAgent: "1" }; // fixed to 1 for testing
    Boat.find(query)
    .then(boats => {
        req.params.boatId = boats[0].boatId;
        var pics;
        picture.findMyBoatPictures(myCall, res, function (pics) { 
            if (pics) {
                console.log("find pics #1 result is " + JSON.stringify(pics));
            } 
            else {
            console.log("find pics #2 result is " + JSON.stringify(pics));
            }
            res.json(boats);
        });
    }).catch(err => {
        console.log("findMyForSale failure is " + JSON.stringify(err));
        res.status(500).send({
            msg: err.message
        });
    });
};

picture.controller.js

const Picture = require('../models/picture.model.js');
exports.findMyBoatPictures = (req, res) => {
    console.log("in boats findMyBoatPictures")
    var query = { owningId: String(req.params.boatId) };
    var orderBy = { sequenceNumber: 1 };
    Picture.find({ owningId: String(req.params.boatId) }).sort({ sequenceNumber: 1 })
        .then(pics => {
            console.log("picture found records: " + pics.length);
            res.json(pics);
        }).catch(err => {
            console.log("picture found error " + err.message);
            res.status(500).send({
                msg: err.message
            });
        });
};

Upvotes: 0

Views: 68

Answers (2)

tbking
tbking

Reputation: 9076

Problem: The picture controller function findMyBoatPictures responds the request with res.json. It doesn't pass the control back to findMyForSale method from which it was called.

Solution: If you have some code to re-use, abstract it in a service which is used by both of the controllers. That service can pass the control back using a callback and then the controllers can respond to the requests with res.json independent of each other.

Upvotes: 1

elraphty
elraphty

Reputation: 630

First of all exports.findMyBoatPictures function accepts two arguments req and res but you are not initiating it correctly, this is what you should do

picture.findMyBoatPictures(req, res);

If u intend getting the value back u have to use a callback function i.e

const Picture = require('../models/picture.model.js');
exports.findMyBoatPictures = (req, res, callback) => {
    console.log("in boats findMyBoatPictures")
    var query = { owningId: String(req.params.boatId) };
    var orderBy = { sequenceNumber: 1 };
   Picture.find({ owningId: String(req.params.boatId) 
}).sort({ sequenceNumber: 1 })
    .then(pics => {
        console.log("picture found records: " + pics.length);
        callback(false, pics)
    }).catch(err => {
        console.log("picture found error " + err.message);
        callback (err)
    });

Then you do

  let pics;
   picture.findMyBoatPictures(req, res, function (err, pics) 
  { 
        if (!err && pics) {
               console.log("find pics #1 result is " + 
              JSON.stringify(pics));
               pics = pics;
           // Send ur response

        } 
        else {
             console.log(err);
            // Send ur response
        }
    });

You can even make it fewer lines of code if you use async and await

Upvotes: 0

Related Questions