简体   繁体   中英

Can't send data to MongoDB from NodeJs

I'm really new to NodeJs and MongoDB or web development in general. I'm following a tutorial on how to make a registration system that was posted about 2 years ago. With these codes below, he was able to send a post request test using postman and his data was saved into MongoDB, however, when I try to send a post request on postman, it keeps loading at "sending request" and data was never saved to mongoDB...I'm not sure if nodejs has changed syntax or if i'm doing something wrong... please help.. this is the code for 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);
            }

    });

this is the code for 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);

this is the code for 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');

In controller you have mongoose to write data to mongo but in your server file you are connecting to mongodb using native mongo driver. Hence, it won't work. Either both places you need to have mongodb native driver or mongoose.

Use below code where I have modified the server start file to use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM