【问题标题】:Can't send data to MongoDB from NodeJs无法从 NodeJs 向 MongoDB 发送数据
【发布时间】: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');

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    在控制器中,您有 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.
    

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      相关资源
      最近更新 更多