我有使用mongoose的node.js,express和MongoDB连接的以下代码。
首先,我尝试使用名为server.js的单个文件,它在没有表达的情况下工作。但是现在我想在快递中做这件事,但它不起作用。
这只是在mongo数据库中读取和创建示例Bear
对象的简单程序。
这是我的 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;
这是我的 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;
请告诉我如何路由CRUD操作。
答案 0 :(得分:2)
你不能在一个文件中有两个module.exports。位于文件底部的那个重写了所有其他文件。
您需要两个文件,例如
控制器/ 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;
模型/ user.js的
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear',BearSchema);
在你的app.js中,你可以这样做:
var user = require('controllers/user');
app.use('/users', user);
它的端点现在在/users/bears
如果你需要你的模型,只需加载
var userModel = mongoose.model('User');
我建议下载并运行此template,当您看到它们已经实现时,更容易添加新功能
答案 1 :(得分:0)
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>