【发布时间】:2020-06-27 06:14:01
【问题描述】:
我对 NodeJs 和 MongoDB 或一般的 Web 开发真的很陌生。我正在关注关于如何制作大约 2 年前发布的注册系统的教程。使用下面的这些代码,他能够使用邮递员发送一个发布请求测试,并且他的数据被保存到 MongoDB,但是,当我尝试在邮递员上发送一个发布请求时,它一直在“发送请求”加载并且数据从未保存到 mongoDB ......我不确定 nodejs 是否改变了语法或者我做错了什么......请帮忙! 这是 user.controller.js 的代码
const mongoose = require('mongoose');
const User = mongoose.model('User');
module.exports.register = (req, res, next) => {
var user = new User();
user.fullName = req.body.fullName;
user.email = req.body.email;
user.password = req.body.password;
user.save((err, doc) => {
if (!err)
res.send(doc);
else {
if (err.code == 11000)
res.status(422).send(['Duplicate email adrress found.']);
else
return next(err);
}
});
这是 user.model.js 的代码:
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
var userSchema = new mongoose.Schema({
fullName: {
type: String
},
email: {
type: String
},
password: {
type: String
},
saltSecret: String
});
// Events
userSchema.pre('save', function (next) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(this.password, salt, (err, hash) => {
this.password = hash;
this.saltSecret = salt;
next();
});
});
});
mongoose.model('User', userSchema);
这是服务器(app.js)的代码
const MongoClient = require('mongodb').MongoClient;
const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
console.log(`MONGODB CONNECTION SUCCEEDED`);
client.close();
});
require('./user.model');
【问题讨论】: