node.js - 数据未持久化/保存到 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}`);
});
解决方案
推荐阅读
- c - strcmp 返回 10 即使字符串相同
- ssis - SSISDB 2019 脚本组件为空白
- bash - 在ansible中转义特殊字符
- django - 如果在 Celery 中将 retry_backoff 设置为 True,max_retries 和 retry_backoff_max 是什么意思?
- postgresql - Postgres:带有可选“WHERE”参数的函数
- php - 如何在php中优先考虑rabbitmq消息?
- java - 使用 iText 签名字段(数字签名与电子签名图像) - 阅读
- java - 根据对象中的变量名而不是字符串正则表达式在springboot中屏蔽敏感数据
- c++ - 推断函数指针的模板参数
- android - 如何在 exoplayer 中实现 OkHttpDataSourceFactory?