我在使用带有注册路由的节点js和mongo db时遇到问题。当我使用失眠发布数据时,它会返回错误:这是它返回的内容
这是我的代码:
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
jwt = require('jsonwebtoken'),
bcrypt = require('bcrypt'),
config = require('./config'),
User = require('./models/user');
//MongoDb configuration
mongoose.connect(config.db, { useNewUrlParser: true }, function(err){
if(err){
console.log(err);
} else {
console.log('Mongo is here for you!');
}
});
//BodyParser configuration
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//Routes
app.get('/', function(req, res){
res.json({
"message": "Welcome to the Node express api!"
});
});
//SignUp
app.post('/signup', function(req, res) {
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
User.create({
email : req.body.email,
password : hashedPassword
},
function (err, user) {
if (err) return res.status(500).send("There was a problem registering the user.")
// create a token
var token = jwt.sign({ id: user._id }, config.secret, {
expiresIn: config.tokenTime // expires in
});
res.status(200).send({ auth: true, token: token });
});
});
//Show all users
app.get('/users', function(req, res) {
User.find({}, function(err, users) {
res.json(users);
});
});
// SERVERHOST
app.listen(3000, function(){
console.log('Node api server has started! :)');
});
这是mongoDb模型:
const mongoose = require('mongoose');
const user = mongoose.Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', user);
也许您遇到了某种模拟错误。请帮助我找出此问题的原因。这段代码工作过一次,我在数据库中注册了一个用户,但之后它只返回这种错误。提前感谢您的帮助!
问题出在"errmsg"中:"E11000 重复键错误索引",表示问题出在数据库中。我刚刚使用用户名更新了架构并删除了旧数据。