NodeJS +猫鼬:尝试将数据添加到数据库后,应用程序挂起(?)

时间:2019-05-09 08:35:04

标签: node.js mongoose

我刚刚了解了NodeJS,ExpressJS和Mongoose。我尝试用它创建一个spring.sleuth.propagation-keys=yourHeaderName 。这是我已经创建的文件:

./ Server.js

RESTful API

./ database / Connect.js

import express from 'express';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import routes from './routes';
import connectDB from './database/connect';

const app = express();
const JWT_SECRET = 'api';

app.use(connectDB);
app.set('secretKey', JWT_SECRET);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(routes);

app.listen(3000, () => {
    console.log('Application is running');
});

./ app / User.js(模型)

import mongoose from 'mongoose';
import chalk from 'chalk';
import dbConfig from '../config/database';

const connected = chalk.bold.cyan;
const error = chalk.bold.yellow;
const disconnected = chalk.bold.red;
const termination = chalk.bold.magenta;

const URI = 'mongodb://127.0.0.1:27017/data_test';
const Options = { 
    useNewUrlParser: true,
};

export default () => {
    mongoose.connect(URI, Options);
    const connection = mongoose.connection;

    connection.on('connected', () => {
        console.log(connected(`Database connection is open to ${URI}`));
    });
    connection.on('error', (err) => {
        console.log(error(`An error has been occured: ${err}`));
    });
    connection.on('disconnected', () => {
        console.log(disconnected('Database connection is disconnected'));
    });
    process.on('SIGINT', () => {
        connection.close(() => {
            console.log(termination('Database connection is disconnected due to application termination'));
            process.exit(0);
        });
    });
};

./ app / controllers / UserController.js

import mongoose from 'mongoose';
import bcrypt from 'bcrypt';

const saltRounds = 10;

// Define a schema
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    name: {
        type: String,
        trim: true,
        required: true
    },
    email: {
        type: String,
        trim: true,
        required: true
    },
    password: {
        type: String,
        trim: true,
        required: true
    },
}, {

});

UserSchema.pre('save', function(next) {
    this.password = bcrypt.hashSync(this.password, saltRounds);
    next();
});

export default mongoose.model('User', UserSchema);

./ routes / index.js

import UserModel from '../User';

class UserController
{
    /**
     * Create a new user
     * 
     * @param {*} req 
     * @param {*} res 
     * @param {*} next 
     */
    store(req, res, next)
    {
        UserModel.create({
            name: req.body.name,
            email: req.body.email,
            password: req.body.password
        }, (err, user) => {
            if (err) {
                next(err);
            } else {
                res.status(200).send({
                    status: 'Success',
                    message: 'User added successfully',
                    data: {
                        user: {
                            id: user.id
                        }
                    }
                });
            }
        });
    }
}

const Controller = new UserController();
export default Controller;

./ routes / user.js

import express from 'express';
import UserRoutes from './user';

const app = express();

app.use('/user', UserRoutes);

app.all('*', (req, res) => {
    res.status(404).send({msg: 'page not found'});
});

export default app;

这就是我已经创建的所有文件,但是我遇到的问题是,当我尝试添加新用户时,它卡在了加载中,而我刚刚添加的新用户也没有进入数据库。

enter image description here

这是日志文件,(根本没有错误,所以我不知道问题出在哪里)。

请帮助,我已经读过Mongoose Documentation,但仍然不知道问题出在哪里。

谢谢

enter image description here

1 个答案:

答案 0 :(得分:1)

这是因为您从connectDB导出的database/Connect.js不是有效的express middleware。使用express时,您必须在中间件中调用next来告诉express转移到下一个中​​间件,否则express会等到您调用它为止。

// You've mounted it like middleware
app.use(connectDB);

// but next is not a param here and you've not invoked.
export default () => {
  ...
  // rest of the code
}

两种修复方法:

不要将其安装为中间件:

connectDB()

或将其设为适当中间件,然后调用next

export default (req, res, next) => {
  ...
  // rest of the code
  // at the end
  next() // <-- important
}