简体   繁体   English

ZCCADDEDB567ABAE643E15DCF0974E503Z controller 无法从存储库中找到方法

[英]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 .我目前在 3 个文件中设置了我的代码: Search.model.jsSearch.repository.jssearch.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.问题是当我向 Route 发送请求时,它到达 controller 但无法调用存储库中的 function。 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 . search.controller.js中的 searchRepo 变量未设置为search.repository.js中的 searchRepository object。 Make sure to export and import that object properly.确保正确导出和导入 object。

You are not importing searchRepo properly in search.controller.js file.您没有在search.controller.js文件中正确导入 searchRepo。

Instead of代替

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

Do this做这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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