我正在开发一个涉及将用户注册到mongodatabase的项目。
我将Mongoose Schema放在一个名为user.js的文件中,这里是代码:
const express = require('express');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const passportLocalMongoose = require('passport-local-mongoose');
let Schema = mongoose.Schema;
let UserSchema = Schema({
name: {
type: String
},
username: {
type: String,
unique: true,
required: true
},
profilePic: {
type: String
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true,
},
usersRecipes: [{type: Schema.Types.ObjectId, ref:'Recipe'}],
userComments: [{type: Schema.Types.ObjectId, ref: 'Recipe'}]
});
let User = mongoose.model('User', UserSchema);
module.exports = User;
我这里是我的文件userRouter.js的代码,我的代码不能正常工作
const express = require('express');
const passport = require('passport');
const User = require('../models/user');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
router = express.Router();
router.get('/', (req, res, next) => {
res.send('Here are the users!')
});
router.get('/:username', (req, res, next) => {
let nameQuery = {username: req.params.username};
User.findOne(nameQuery, (err, user) =>{
if (err) throw err;
res.json(user);
})
});
router.post('/register', function(req, res, next, err){
User.create({
username: req.body.username,
password: req.body.password,
name: req.body.name,
email: req.body.email,
profilePic: req.body.profilePic
}, (err, user) => {
if (err) return err;
res.json(user);
});
});
module.exports = router;
这是我的app.js文件:
let express = require('express');
let mongoose = require('mongoose');
let path = require('path');
let bodyParser = require('body-parser');
let recipeRouter = require('./routes/recipeRouter');
let userRouter = require('./routes/userRouter');
let bcrypt = require('bcrypt');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let config = require('./config');
mongoose.connect(mongodb://localhost:27017);
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
const app = express();
const port = 3000;
app.listen(port);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.set('views', path.join(__dirname, 'views'));
app.use('/users', userRouter);
app.use('/recipes',recipeRouter);
app.get('/', function(req, res){
res.send('Hey, this is your database!')
});
module.exports = app;
我做错了什么?
答案 0 :(得分:1)
这是问题所在:
router.post('/register', function(req, res, next, err) { ... })
具体来说,是第四个err
参数。传递一个带有4个参数的函数对Express具有内部意义,这意味着该函数是一个错误处理程序,在这种情况下它不是。
请改用:
router.post('/register', function(req, res, next) { ... })
此外,稍后您的代码:
if (err) return err;
您可能想要抛出该错误(或致电return next(err)
)。