首页 > 解决方案 > 无法从 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');

标签: node.jsmongodb

解决方案


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

推荐阅读