node.js - 无法从 NodeJs 向 MongoDB 发送数据
问题描述
我对 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');
解决方案
在控制器中,您有 mongoose 将数据写入 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.
推荐阅读
- sql - 将视图从 SQL Server(本地)复制到 Azure SQL Server
- reactjs - 无法获取未定义或空引用的属性“绑定”
- php - 动态渲染视图 symfony5
- python - 如何使用 Anaconda / pip 组织我的 Python 库
- c - 将字符串从 const char *const 数组复制到字符串(在 C 中)
- javascript - 仅当我更新数据两次时,反应材料表才用新数据重新渲染表
- rust - const fn 与内联属性
- c# - 是否有包含两者的类型:列表
还有 HashSet ? - php - 如何在php中限制表单提交的文件上传大小
- mongodb - Mongo DB 平均值