数据无法持久保存/保存到MongoDB数据库中

时间:2019-12-29 02:39:32

标签: node.js mongodb

尽管要调用.save()方法,我还是想弄清楚为什么我的数据没有保存在MongoDB中。我知道这是一个异步过程,但是正如您在下面看到的那样,我使用.then()设置了一个回调,该回调执行没有错误。目标数据库中只有一个空集合,因此我希望数据会出现在该数据库中或出现在一个新集合中,但都没有发生。这是我的index.js文件的代码:

const express = require('express');
const mongoose = require('mongoose');
const { body, validationResult } = require('express-validator/check');

const router = express.Router();
const Registration = mongoose.model('Registration');

router.get('/', (req, res) => {
    res.render('form', { title: 'Registration Form'});
  });

router.post('/', 
  [body('name')
    .isLength(1)
    .withMessage('Please enter a name.'),

  body('email')
    .isLength(1)
    .withMessage('Please enter an email address.')
  ],
    (req, res) => {
    //console.log(req.body);
    const errors = validationResult(req);

    if(errors.isEmpty)
    {
      const registration = new Registration(req.body);
      //registration.markModified('collection_1');
      registration.save()
        .then(() => { res.send('Thank you for your registration!'); })
        .catch(() => { res.send('Sorry! Something went wrong.'); });
    } else {
      // re-renders form with error message
      res.render('form', {
        title: 'Registration form',
        errors: errors.array(),
        data: req.body,
      });
    }
  });

module.exports = router;

让我知道是否还有其他文件有用。任何帮助将不胜感激。

编辑:这是我的start.js文件。

require('dotenv').config();
const mongoose = require('mongoose');
require('./models/Registration');

mongoose.connect(process.env.DATABASE, { useMongoClient: true });
mongoose.Promise = global.Promise;
mongoose.connection
  .on('connected', () => {
    console.log(`Mongoose connection open on ${process.env.DATABASE}`);
  })
  .on('error', (err) => {
    console.log(`Connection error: ${err.message}`);
  });

const app = require('./app');
const server = app.listen(3000, () => {
  console.log(`Express is running on port ${server.address().port}`);
});

0 个答案:

没有答案