首页 > 解决方案 > 数据未持久化/保存到 MongoDB 数据库中

问题描述

我试图弄清楚为什么我的数据没有保存在 MongoDB 中,尽管调用了该.save()方法。我知道这是一个异步过程,但正如您在下面看到的,我使用.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}`);
});

标签: node.jsmongodb

解决方案


推荐阅读