getting an error while running as .find is not a function

340 Views Asked by At

I am trying clean architecture and just till created the rest API. I am using node js, mongoose, and express. While running getting an error in the controller. Attaching my code. I am new to this so sorry in advance if there any mistake src/controllers/campaignController.js

const campaigndb = require("../models/index");
const Campaign = campaigndb.campaigns;

// Create and Save a new Campaign
exports.create = (req, res) => {
    // Validate request
    if (!req.body.beneficiary_name) {
      return res.status(400).send({ message: "Content can not be empty!" });
      
    }
  
    // Create a campaign
    const campaign = new Campaign({
        beneficiary_name: req.body.beneficiary_name,
        beneficiary_type: req.body.beneficiary_type,
        beneficiary_avatar: req.body.beneficiary_avatar,
        audio_call: req.body.audio_call
      
    });
  
    // Save campaign in the database
    campaign.save()
      .then(data => {
        res.send(data);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error"
        });
      });
  };

// Retrieve all campaign from the database.
exports.findAll = (req, res) => { 
    Campaign.find()
      .then(campaigns => {
        res.send(campaigns);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error"
        });
      });
  };
// Find a single campaign with an id
exports.findOne = (req, res) => {
        const id = req.params.id;
      
        Campaign.findById(id)
          .then(data => {
            if (!data)
              res.status(404).send({ message: "Not found " + id });
            else res.send(data);
          })
          .catch(err => {
            res
              .status(500)
              .send({ message: "Error retrieving with id=" + id });
          });
      };


// Update a campaign by the id in the request
exports.update = (req, res) => {
    if (!req.body) {
      return res.status(400).send({
        message: "Data to update can not be empty!"
      });
    }
  
    const id = req.params.id;
  
    Campaign.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
      .then(data => {
        if (!data) {
          res.status(404).send({
            message: `Cannot update campaign with id=${id}`
          });
        } else res.send({ message: "Campaign was updated successfully." });
      })
      .catch(err => {
        res.status(500).send({
          message: "Error updating campaign with id=" + id
        });
      });
  };

..env/db.js

 module.exports={
        url:"mongodb://localhost:27017/campaign_db"
    }

campaignModel.js

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
        const campaignSchema = new Schema({
                beneficiary_name:{ type:String },
                beneficiary_type:{ type:String },
                beneficiary_avatar:{ type:String},
                audio_url:{ type:String}
        });
        campaignSchema.method("toJSON", function() {
            const { __v, _id, ...object } = this.toObject();
            object.id = _id;
            return object;
          });
        
        // use id instead of _id globally then you can set toJSON config on mongoose object
        
      
module.exports = mongoose.model('Campaign', campaignSchema);

src/model/index

const dbConfig = require("../env/db.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const campaigndb = {};
campaigndb.mongoose = mongoose;
campaigndb.url = dbConfig.url;
campaigndb.campaigns = require("./campaignModel.js")(mongoose);

module.exports = campaigndb;

src/route/index.js

const campaigns = require('./campaignRoute');

exports.campaignRoutes = function (app) {
    app.post('/campaigns', campaigns.createCampaign);
}

src/route/campaignRoute.js

module.exports = app => {
    const campaigns = require("../controllers/campaignController.js");
  
    const router = require("express").Router();
  
    // Create a new campaign
    router.post("/", campaigns.create);
  
    // Retrieve all campaigns
    router.get("/", campaigns.findAll);
  
    // Retrieve all published campaigns
    router.get("/findAllCampaign", campaigns.findAllCampaign);
  
    // Retrieve a single campaign with id
    router.get("/:id", campaigns.findOne);
  
    // Update a campaign with id
    router.put("/:id", campaigns.update);
  
    app.use('/api/campaigns', router);
  };

getting error in findAll enter image description here

Please anyone help me out?Thanks in advance

1

There are 1 best solutions below

2
On

Can you try passing an empty object to findAll function like so:

// Retrieve all campaign from the database.
exports.findAll = (req, res) => { 
    Campaign.find({}) //<---------------------------pass {} to find
      .then(campaigns => {
        res.send(campaigns);
      })
      .catch(err => {
        res.status(500).send({
          message:
            err.message || "Some error"
        });
      });
  };