Проблема с созданием почтового запроса в CRUD - PullRequest
0 голосов
/ 12 декабря 2018

Вот мой код:

//server.js
const express = require('express'),
          cors = require('cors'),
          bodyParser = require('body-parser'),
          mongoose = require('mongoose');


const Mate = require('./models/mate');


mongoose.Promise = global.Promise;


const app = express();
const router = express.Router();

app.use(cors());
app.use(bodyParser.json())

mongoose.connect('mongodb://localhost:27018/mate', {useNewUrlParser: true});

const connection = mongoose.connection;

connection.once('open', () => {
    console.log('Mongodb db connection established succ');
})

router.route('/mate').get((req, res) => {
    mongoose.model('Mate').find((err, mate) =>  {
        if (err) 
            console.log(err);
        else
            res.json(mate);
    });
});

router.route('/mate/:id').get((req, res) => {
    mongoose.model('Mate').findById((err, mate) => {
        if(err)
            console.log(err);
        else
            res.json(mate);
    });
});

router.route('/mate/add').post(async (req, res) => {
        try {
            const mate = new Mate(req.body);
            await mate.save();
            res.status(200).json({
                'mate:': 'Added succesfully'
            });
        } catch (err) {
            console.log(err);
            res.status(400).send( 'failed to create' );
        }
}); 

router.route('mate/update/:id').post((req, res) => {
    mongoose.model(Mate).findById(req.params.id, (err, mate) =>{
        if(!mate)
            return next(new Error('couldnt load doc'))
        else {
            mate.title = req.body.title;
            mate.day = req.body.day;
            mate.severity = req.body.severity;
            mate.status = req.body.status;

            mate.save().then(mate => {
                res.json('Update done');
            }).catch(err => {
                res.status(400).send('update failed');
            });
        }
    });
});

router.route('mate/delete/:id').get((req, res) => {
    mongoose.model(Mate).findByIdAndRemove({_id: req.params.id}, (err, mate) => {
        if(err)
            res.json(err);
        else
            res.json('Removed');
    });
});

app.use('/', router);

app.listen(4000, () => console.log('server running on port 4000'));

//mate.js

const mongoose = require('mongoose')

const Schema = mongoose.Schema;

let MateSchema = new Schema({
    title: {
        type: String
    },
    day: {
        type: String
    },
    severity: {
        type: String
    },
    status: {
        type: String, 
        default: 'Open'
    }
});

module.export = mongoose.model('Mate', MateSchema);

Таким образом, в основном проблема заключается в добавлении контроллера в server.js, который должен выдавать пост-запрос в мою БД с созданным новым json.Ну, это не так, но выдает эту ошибку: TypeError: Mate не является конструктором;

Помогите, пожалуйста, выяснить, почему так происходит.Я новичок в коде, так что это может быть глупый вопрос, но я застрял в этом.

Ответы [ 2 ]

0 голосов
/ 12 декабря 2018

Внести изменения в модуль экспорта как:

module.export = Mate = mongoose.model('Mate', MateSchema);
0 голосов
/ 12 декабря 2018

сделать mate.js как показано ниже

module.exports = function(mongoose) {

    var options = {
    collection: 'mate',
    timestamps: {
      createdAt: 'created_on',
      updatedAt: 'updated_on'
    },
    toObject: {
      virtuals: true
    },
    toJSON: {
      virtuals: true
    }
  };

let MateSchema = new mongoose.Schema({
    title: {
        type: String
    },
    day: {
        type: String
    },
    severity: {
        type: String
    },
    status: {
        type: String, 
        default: 'Open'
    }
});



return MateSchema;
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...