Joe Early
Joe Early

Reputation: 116

mongoose find all not sending callback

new mongoose and I am finding the Modal.find() a little troublesome.

I have a expressjs api endpoint /latest/all that should return all products in my mongodb.

// Get latest listings
  router.get('/latest/all', function (req, res, next) {
  var json = Product.getAllProductListings();

  res.send(json);
});

The below is a product.js modal.

   'use strict';

var mongoose = require('mongoose');


// Product Schema
var ProductSchema = mongoose.Schema({
    category: {
        type: String,
        index: true
    },
    name: {
        type: String
    },
    state: {
        type: String
    },
    target: {
        type: String
    }
});

var Product = module.exports = mongoose.model('Product', ProductSchema);

//Add new product request
module.exports.createProductReq = function (newProdReq, callback) {

    newProdReq.save(callback);

};


//Find all products


//Find One
module.exports.getProductByCategory = function (category, callback) {
    var query = {category: category};
    Product.findOne(query, callback);
};

//Find All
module.exports.getAllProductListings = function (docs) {
    var query = {};
    Product.find(query, function (err, docs) {
        console.log(docs);
    });


};

The console.log(docs); displays what I expect it too in my console window, however the "docs" is not being passed to the getAllProductListings in the same fashion as the "findOne" before hand.

I have only one return value in the function for getAllProductListings since it doesn't take parameters.

Am definitely doing something silly so please enlighten me if you can.

Upvotes: 1

Views: 131

Answers (1)

Hamza Fatmi
Hamza Fatmi

Reputation: 1255

Because getAllProductListings is asynchronous, you need to send the response in the callback :

// Get latest listings
router.get('/latest/all', function (req, res, next) {
Product.getAllProductListings(res);
});

And in your product.js :

//Find All
module.exports.getAllProductListings = function (response) {
var query = {};
Product.find(query, function (err, docs) {
    console.log(docs);
    response.send(docs);
});

Upvotes: 1

Related Questions