Проблемы с использованием моделей Sequelize, ошибки типа «Невозможно прочитать свойство 'create' of undefined" или Client не определены - PullRequest
0 голосов
/ 06 января 2019

У меня проблемы с использованием моделей Sequelize для моего Crud, у меня есть такие ошибки, как «Невозможно прочитать свойство 'create' of undefined" или "Клиент не определен", и я действительно не знаю, что я делаю неправильно, мой код:

index.js

"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");
var env       = process.env.NODE_ENV || "development";
var config    = require(path.join(__dirname, '..', 'config', 'config.json'))[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db        = {};


fs
  .readdirSync(__dirname)
  .filter(function(file) {
    return (file.indexOf(".") !== 0) && (file !== "index.js");
  })
  .forEach(function(file) {
    var model = sequelize.import(path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(function(modelName) {
  if ("associate" in db[modelName]) {
    db[modelName].associate(db);
  }
});


db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

мой клиентский класс

module.exports = function(sequelize, Sequelize) {

    const Client = sequelize.define('client', {
        cardcode: { primaryKey: true, type: Sequelize.STRING },
        Cardname: { type: Sequelize.STRING, notEmpty: true },
        address: { type: Sequelize.STRING, notEmpty: true },
        country: { type: Sequelize.STRING, notEmpty: true },
        cargo: { type: Sequelize.STRING, notEmpty: true },
        Tel: { type: Sequelize.STRING, notEmpty: true },
        FirstName: { type: Sequelize.STRING, notEmpty: true },
        LastName: { type: Sequelize.STRING, notEmpty: true },
        E_MailL: { type: Sequelize.STRING, notEmpty: true },
        clienteNuevo: { type: Sequelize.INTEGER, allowNull: false }

    });

    return Client;

}

мой клиентский контроллер

const Client = require('../models/client.model').Client;


// Post a Customer
exports.create = (req, res) => {
    // Save to MariaDB database
    Client.create({
            cardcode: req.body.cardcode,
            Cardname: req.body.Cardname,
            address: req.body.address,
            country: req.body.country,
            cargo: req.body.cargo,
            Tel: req.body.Tel,
            FirstName: req.body.FirstName,
            LastName: req.body.LastName,
            E_MailL: req.body.E_MailL,
            clienteNuevo: req.body.clienteNuevo
        })
        .then(client => {
            // Send created customer to client
            res.satus(200).json({ message: 'Client Created Successfull', client });
        })
        .catch(error => res.status(400).send(error))
};

// Fetch all Customers
exports.findAll = (req, res) => {
    Customer.findAll({
            attributes: { exclude: ["createdAt", "updatedAt"] }
        })
        .then(client => {
            res.json(client);
        })
        .catch(error => res.status(400).send(error))
};

// Find a Customer by Id
exports.findById = (req, res) => {
    Client.findById(req.params.cardcode, { attributes: { exclude: ["createdAt", "updatedAt"] } })
        .then(client => {
            if (!client) {
                return res.status(404).json({ message: "Client Not Found" })
            }
            return res.status(200).json(client)
        })
        .catch(error => res.status(400).send(error));
};

// Update a Customer
exports.update = (req, res) => {
    return Client.findById(req.params.cardcode)
        .then(
            client => {
                if (!client) {
                    return res.status(404).json({
                        message: 'Customer Not Found',
                    });
                }
                return client.update({
                        Cardname: req.body.Cardname,
                        address: req.body.address,
                        country: req.body.country,
                        cargo: req.body.cargo,
                        Tel: req.body.Tel,
                        FirstName: req.body.FirstName,
                        LastName: req.body.LastName,
                        E_MailL: req.body.E_MailL,
                    })
                    .then(() => res.status(200).json(client))
                    .catch((error) => res.status(400).send(error));
            }
        )
        .catch((error) => res.status(400).send(error));
};

// Delete a Customer by Id
exports.delete = (req, res) => {
    return Client
        .findById(req.params.cardcode)
        .then(client => {
            if (!client) {
                return res.status(400).send({
                    message: 'Customer Not Found',
                });
            }

            return client.destroy()
                .then(() => res.status(200).json({ message: "Destroy successfully!" }))
                .catch(error => res.status(400).send(error));
        })
        .catch(error => res.status(400).send(error));
};

мой клиент маршруты

module.exports = function(app, passport) {
    const clients = require('../controllers/client.controller.js');

    // Create a new Customer
    app.post('/users/clients/create', isValidUser, clients.create);

    // Retrieve all Customer
    app.get('/users/clients', isValidUser, clients.findAll);

    // Retrieve a single Customer by Id
    app.get('/users/clients/:cardcode', isValidUser, clients.findById);

    // Update a Customer with Id
    app.put('/users/clients/:cardcode', isValidUser, clients.update);

    // Delete a Customer with Id
    app.delete('/users/clients/:cardcode', isValidUser, clients.delete);


    function isValidUser(req, res, next) {
        if (req.isAuthenticated()) next();
        else return res.status(401).json({ message: 'Please Log In' });
    }
}

У меня нет проблем с использованием пользователей с passportJs, но я действительно не могу использовать модели на своих контроллерах ...

...