简体   繁体   中英

How to route CRUD operations in express?

I have the following code for node.js, express, and a MongoDB connection using mongoose.

Firstly I try on a single file named server.js and it's working without express. But now I want to do it in express but it's not working.

It's just simple program that read and create sample Bear objects in mongo database.

Here it is my app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

//var routes = require('./routes/index');
var users = require('./routes/users');
var mongoose = require('mongoose');
var db = mongoose.connect('localhost:27017/nodetest1');

//var Bear = require('./routes/users');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

var port = process.env.PORT || 8080;

// Make our db accessible to our router
app.use(function(req,res,next){
    req.db = db;
    next();
});

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

router.use(function(req,res,next){
  console.log('something is happening');
  next();
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});

// more routes for our API will happen here




// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api

app.use('/', router);
app.use('/bears', users);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});


module.exports = app;

and here it is my users.js

var express = require('express');
var router = express.Router();

var Schema = mongoose.Schema;

var BearSchema = new Schema({
  name: String
});

module.exports = mongoose.model('Bear',BearSchema);


router.route('/bears')

    // create a bear (accessed at POST http://localhost:8080/api/bears)
    .post(function(req, res) {

        var bear = new Bear();      // create a new instance of the Bear model
        bear.name = req.body.name;  // set the bears name (comes from the request)

        // save the bear and check for errors
        bear.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Bear created!' });
        });

    });
module.exports = router;

Please tell me how to route the CRUD operations.

You cant have two module.exports in one file. The one, which is at the bottom of file rewrites all others.

You need two files, something like

controllers/users.js

var express = require('express');
var router = express.Router();

router.route('/bears')

    // create a bear (accessed at POST http://localhost:8080/api/bears)
    .post(function(req, res) {

        var bear = new Bear();      // create a new instance of the Bear model
        bear.name = req.body.name;  // set the bears name (comes from the request)

        // save the bear and check for errors
        bear.save(function(err) {
            if (err)
                res.send(err);

            res.json({ message: 'Bear created!' });
        });

    });
module.exports = router;

models/user.js

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

var BearSchema = new Schema({
  name: String
});

module.exports = mongoose.model('Bear',BearSchema);

In your app.js, you can do this :

var user = require('controllers/user');
app.use('/users', user);

It endpoint now listen at /users/bears

If you need your model somewhere, just load it with

var userModel = mongoose.model('User');

I would recommend to download and run this template , it is more easily to add new features, when you see, how they are already implemented

CRUD operation nodejs expressjs mongodb mongoose - Video Tutorial

models/emp.js

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

var conn = mongoose.Collection;
var empSchema = new mongoose.Schema({
    name: String,
    email: String,
    age: String,
    gender: String
});

var empModel = mongoose.model('Emp', empSchema);
module.exports = empModel;

routes/index.js

var express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
var empModel = require('../models/emp');
mongoose.connect("mongodb://localhost:27017/employee", { useNewUrlParser: true, useUnifiedTopology: true });

router.get('/', function(req, res, next) {
  empModel.find({}, function(err, docs) {
    res.render('index', { title: 'Express', result:docs });
  })
});

router.post('/', function(req, res, next) {
 const emp = new empModel({
    name: req.body.name,
    email: req.body.email,
    age: req.body.age,
    gender: req.body.gender
    });
emp
.save()
.then(result => {
  res.redirect("/");
})
.catch(err => {
res.status(500).json({ error: err });
});
});

router.get('/update', function(req, res, next) {
  empModel.find({},function(err, docs) {
    res.render('update', { title: 'Express', result: docs });
  })
});

router.post('/update', function(req, res, next) {
empModel.findOneAndUpdate({ email: req.body.email },{ $set: { name: req.body.name, age: req.body.age, gender:req.body.gender } },{ returnOriginal: false }).exec().then(result => {
res.redirect("/");
 }).catch(err => {
  res.status(500).json({ error:err });
 });
});

router.get('/delete', function(req, res, next) {
  empModel.find({},function(err, docs) {
    res.render('delete', { title: 'Express', result: docs });
  })
});

router.post('/delete', function(req, res, next) {
  empModel.remove({ email: req.body.email }).exec().then(result => {
    res.redirect("/");
   }).catch(err => {
  res.status(500).json({ error:err });
 });
});
module.exports = router;

views/index.js

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
          <title><%= title %></title>
        <style>
        .login-form {
            width: 300px;
            margin: 0 auto;
            font-family: Tahoma, Geneva, sans-serif;
        }
        .login-form h1 {
            text-align: center;
            color: #4d4d4d;
            font-size: 24px;
            padding: 20px 0 20px 0;
        }
        .login-form input[type="password"],
        .login-form input[type="text"] {
            width: 100%;
            padding: 15px;
            border: 1px solid #dddddd;
            margin-bottom: 15px;
            box-sizing:border-box;
        }
        .login-form input[type="submit"] {
            width: 100%;
            padding: 15px;
            background-color:red;
            border: 0;
            box-sizing: border-box;
            cursor: pointer;
            font-weight: bold;
            color: #ffffff;
        }
        </style>
 <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<meta charset="UTF-8">
<meta name="description" content="sotre">
<meta name="keywords" content="">
<meta name="author" content="">
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0">  -->
</head>
    <body>
    <nav class="navbar navbar-light bg-light">
    <a class="navbar-brand" href="/">
    <%= title %>
    </a>
    <ul class="list-unstyled list-inline pull-right">
    </nav>
        <div class="row">
            <div class="col-md-6">
                <table class="table  table-condensed" width="100%"  >
            <thead>
                <tr>
                <th>Sr</th>
                <th>Name</th>
                <th>Email</th>
                <th>Age</th>
                <th>Gender</th>
                </tr>
                    </thead>
                    <tbody>
                        <% if(result.length){ 
                    for(var i = 0;i < result.length;i++) { %>
                        <tr>
                        <td><%=i+1%></td>

                         <td><%=result[i].name%></td>
                             <td><%=result[i].email%></td>
                        <td><%=result[i].age%></td>
                        <td><%=result[i].gender%></td>

                </tr>   <%}}%>
                    </tbody>
                  </table>
            </div>
            <div class="col-md-6">
            <div class="login-form">
            <h1>CRUD OPERATION</h1>
                 <ul class="nav nav-tabs">
                    <li class="active"><a href="/">Insert</a></li>
                    <li><a href="/update">Update</a></li>
                    <li><a href="/delete">Delete</a></li>
                 </ul>
            <form action="/" method="POST">
                <input type="text" name="name" placeholder="Name" required>
                <input type="text" name="email" placeholder="Email" required>
                <input type="text" name="age" placeholder="Age" required>
                <input type="text" name="gender" placeholder="Gender" required>
                <input type="submit" value="Insert" class="btn btn-primary">
            </form>

        </div>
            </form>
            </div>
        </div>
    </body>
</html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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