简体   繁体   中英

Mongoose controller cant find a method from Repository

I currently have my code setup in 3 files: Search.model.js , Search.repository.js , and search.controller.js .

The issue is when I send a request to the Route it reaches the controller but cannot call the function in the Repository. The code is below:

search.repository.js

const mongoose = require('mongoose');
const Search = require('../models/search.model');
const perPage = config.PAGINATION_PERPAGE;

const searchRepository = {
    save: async (data) => {
        console.log("Reached save in Repository");
        try {
            let record = await Search.create(data);
            if (!record) {
                return null;
            }
            return record;
        } catch (e) {
            throw e;
        }
    },
};
module.exports = searchRepository;

search.controller.js

const mongoose = require("mongoose");
const searchRepo = "../repositories/search.repository";

class SearchController  {
constructor() {}

async store(req) {
  console.log("Reached Store");
    try{
      let record = await searchRepo.save(req.body);
      if (record) {
        return { status: 200, data: {}, message: "Saved Successfully" };
      } else {
        return { status: 201, data: {}, message: "Unable to save your record. Please try again later." };
      }
    }
    catch(e){
      return { status: 201, data: {}, message: e.message };
    }
}
}
module.exports = new SearchController();

The error I get:

{
    "status": 201,
    "data": {},
    "message": "searchRepo.save is not a function"
}

The searchRepo variable in search.controller.js is not set to the searchRepository object found in search.repository.js . Make sure to export and import that object properly.

You are not importing searchRepo properly in search.controller.js file.

Instead of

const searchRepo = "../repositories/search.repository";

Do this

const searchRepo = require("../repositories/search.repository");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM