【问题标题】:getting an error while running as .find is not a function作为 .find 运行时出现错误不是函数
【发布时间】:2020-10-19 06:46:10
【问题描述】:

我正在尝试干净的架构,直到创建了其余的 API。我正在使用节点 js、猫鼬和 express。运行时在控制器中出现错误。附上我的代码。我是新手,如果有任何错误,请提前道歉 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/模型/索引

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);
  };

在 findAll 中出现错误

请任何人帮助我吗?在此先感谢

【问题讨论】:

    标签: node.js mongoose rest clean-architecture


    【解决方案1】:

    您可以尝试像这样将一个空对象传递给findAll 函数吗:

    // 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"
            });
          });
      };
    

    【讨论】:

    • src/model/index.js中,您可以在分配广告系列时添加new关键字吗:campaigndb.campaigns = new require("./campaignModel.js")(mongoose);
    • 请任何人帮助我?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-17
    • 2016-08-08
    • 2016-06-14
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多