.save函数无法正常工作而不会将数据插入到表的集合中。当我使用mongodb命令将数据插入集合时,数据正在插入。我也在检查它的工作正常的猫鼬连接。当我在.save函数中使用else情况时,它将进入其他条件但数据不插入。模型和路线代码正在帮助解决这个问题。
var express = require('express');
var router = express.Router();
var User = require('../model/User');
var bcrypt = require('bcryptjs');
/* GET users listing. */
router.get('/register', function(req, res, next) {
res.render('register', {title: 'User registrations page !'});
});
router.get('/login', function(req, res, next){
res.render('login', {title: 'User Login page !'});
});
//Register process
router.post('/register', function (req, res) {
var name = req.body.fullname;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var newUser = new User();
newUser.name = name;
newUser.email = email;
newUser.username = username;
newUser.password = password;
newUser.save(function(err, savedUser){
if (err) {
console.log(err);
return res.status(500).send();
}
return res.status(200).send();
});
});
Creating a model user under the model folder which is including in users routes file
var mongoose = require('mongoose');
var userSchema = mongoose.Schema({
name:{
type: String,
required: true
},
email:{
type: String,
required: true
},
username:{
type: String,
required: true
},
password:{
type: String,
required: true
}
});
var user = mongoose.model('myuser', userSchema);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/userDet',{ useMongoClient: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(err) {
if (err) {
console.log('Connection error');
}
// we're connected!
else {
console.log('We are connected !');
}
});
module.exports = user;
答案 0 :(得分:0)
@NiteshSingh当你想从html表单中获取数据时需要进行解析。确保html form
代码action
必须与post route
<form method="post" action="/register">
相同。试试这段代码
var express = require('express');
var bodyParser = require('body-parser');
var mongoose=require('mongoose');
var User=require('../models/User');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var userRouter = express.Router();
userRouter.use(bodyParser.json());
userRouter.post('/register',urlencodedParser,function(req, res, next){
var myData = new User(req.body);
myData.save()
.then(item => {
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
app.use('/register',userRouter);
module.exports = userRouter;
您可以点击此链接https://medium.com/@ratracegrad/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073 从上到下阅读本文。你会明白的。希望这会有所帮助...