如何通过控制器和路由类使用Node JS进行Crud操作

时间:2019-06-04 15:55:36

标签: controller routes nodes

我是nodejs语言的新手。我想知道如何使用控制器和节点中的路由类进行基本的Crud操作。

4 个答案:

答案 0 :(得分:0)

user.route.js

var express     = require('express');
var router      = express.Router();
var controller  = require('./user.controller');

//get all courses
router.get('/getAllCourse', (req, res) => {
controller.getAllCourses().then(response => {
    res.status(response.status).send(response);
}).catch(err => {
    res.status(err.status).send(err.message);
})
});

//add new course
router.post('/addNewCourse', (req, res) => {
controller.addCourse(req.body).then(response => {
    res.status(response.status).send(response.message);
}).catch(err => {
    res.status(err.status).send(err.message);
})
});

//get course details by course code
router.get('/get_specific_course/:id', (req, res) => {
controller.getSpecificCourse(req.params.id).then(response => {
    res.status(response.status).send(response.data);
}).catch(err => {
    res.status(err.status).send(err.message);
})
});

//update
router.put('/:id', (req, res) => {
controller.update(req.params.id, req.body).then(response => {
    res.status(response.status).send(response);
}).catch(err => {
    res.status(err.status).send(err.message);
})
});

//delete test request
router.delete('/:id', (req, res) => {
controller.deleteTestReq(req.params.id).then(response => {
    res.status(response.status).send(response);
}).catch(err => {
    res.status(err.status).send(err.message);
})
})

答案 1 :(得分:0)

User.controller.js

var mongoose    = require('../mongoose.config');
var UserSchema  = mongoose.model('User');
var UserSchema2 = mongoose.model('Specimen');
var testReqSchema = mongoose.model('TestRequest');
var patientSchema = mongoose.model('Patient');
var courseSchema = mongoose.model('course');
var subjectSchema = mongoose.model('subject');
var UserController = function() {

this.add = function(userInstance) {
    return new Promise((resolve, reject) => {
        var user = new UserSchema({
            name: userInstance.name
        })
        user.save().then(() => {
            resolve({'status': 200, 'message':'added new user'});
        }).catch(err => {
            reject({'status': 404, 'message':'err:-'+err});
        })
    })
}
//get all course
this.getAllCourses=function(){
return new Promise((resolve, reject) => {
    courseSchema.find().exec().then(data => {
                        resolve({'status': 200, 'message':'get all course    
data', 'data': data});
    }).catch(err => {
                        reject({'status': 404, 'message':'err:-'+err});
    })
    })
}
//get specific course details
this.getSpecificCourse = function(id){
return new Promise((resolve, reject) => {
    courseSchema.find({code: id}).exec().then(data => {
                        resolve({'status': 200, 'message':'get single data',   
'data': data});
    }).catch(err => {
                        reject({'status': 404, 'message':'err:-'+err});
                })
})
}
//update
this.update = function(id, updateData) {
    return new Promise((resolve, reject) => {
        UserSchema.update({_id: id}, updateData).then(() => {
            resolve({'status': 200, 'message':'update user'});
        }).catch(err => {
            reject({'status': 404, 'message':'err:-'+err});
        })
    })
}
this.delete = function(id) {
    return new Promise((resolve, reject) => {
        UserSchema.remove({_id: id}).then(() => {
            resolve({'status': 200, 'message':'delete user'});
        }).catch(err => {
            reject({'status': 404, 'message':'err:-'+err});
        })
    })
}

}

答案 2 :(得分:0)

检查这一希望,这将有助于您澄清

server.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;

let Todo = require('./todo.model');

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

mongoose.connect('mongodb://127.0.0.1:27017/todos', { useNewUrlParser: true });
const connection = mongoose.connection;

connection.once('open', function() {
    console.log("MongoDB database connection established successfully");
})

todoRoutes.route('/').get(function(req, res) {
    Todo.find(function(err, todos) {
        if (err) {
            console.log(err);
        } else {
            res.json(todos);
        }
    });
});

todoRoutes.route('/:id').get(function(req, res) {
    let id = req.params.id;
    Todo.findById(id, function(err, todo) {
        res.json(todo);
    });
});

todoRoutes.route('/add').post(function(req, res) {
    let todo = new Todo(req.body);
    todo.save()
        .then(todo => {
            res.status(200).json({'todo': 'todo added successfully'});
        })
        .catch(err => {
            res.status(400).send('adding new todo failed');
        });
});

todoRoutes.route('/update/:id').post(function(req, res) {
    Todo.findById(req.params.id, function(err, todo) {
        if (!todo)
            res.status(404).send('data is not found');
        else
            todo.todo_description = req.body.todo_description;
            todo.todo_responsible = req.body.todo_responsible;
            todo.todo_priority = req.body.todo_priority;
            todo.todo_completed = req.body.todo_completed;

            todo.save().then(todo => {
                res.json('Todo updated');
            })
            .catch(err => {
                res.status(400).send("Update not possible");
            });
    });
});

app.use('/todos', todoRoutes);

app.listen(PORT, function() {
    console.log("Server is running on Port: " + PORT);
});

答案 3 :(得分:0)

这是为mongodb配置todo.model.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let Todo = new Schema({
    todo_description: {
        type: String
    },
    todo_responsible: {
        type: String
    },
    todo_priority: {
        type: String
    },
    todo_completed: {
        type: Boolean
    }
});

module.exports = mongoose.model('Todo', Todo);