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"
}
CodePudding user response:
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. It is currently only set to a string. Instead, you could use require
(ex. require({file_path}).{identifier}
to import it.
CodePudding user response:
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");