저는 NodeJ와 MongoDB 또는 일반적으로 웹 개발을 처음 접했습니다. 약 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);
이것은 server (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');
컨트롤러에는 mongo에 데이터를 쓰는 몽구스가 있지만 서버 파일에서는 기본 mongo 드라이버를 사용하여 mongodb에 연결합니다. 따라서 작동하지 않습니다. 두 곳 모두 mongodb 네이티브 드라이버 또는 mongoose가 필요합니다.
몽구스를 사용하도록 서버 시작 파일을 수정 한 아래 코드를 사용하십시오.
const mongoose = require('mongoose'),
const m_url = 'mongodb://127.0.0.1:27017/',
db_name = 'test', // use your db name
m_options = {
'auto_reconnect': true,
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
mongoose.connect(m_url + db_name, m_options, function (err) {
if (err) {
console.log('Mongo Error ' + err);
} else {
status.mongo = 'Running'
console.log('MongoDB Connection Established');
}
});
// import/require user controller.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다