Node.js 数据未持久化/保存到MongoDB数据库
尽管调用了Node.js 数据未持久化/保存到MongoDB数据库,node.js,mongodb,Node.js,Mongodb,尽管调用了.save()方法,我仍在试图找出为什么我的数据没有保存在MongoDB中。我知道这是一个异步过程,但正如您在下面看到的,我使用.then()-设置了一个回调,它执行时不会出错。目标数据库中只有一个空集合,因此我希望数据出现在那里或新集合中,但这两种情况都没有发生。下面是我的index.js文件的代码: const express = require('express'); const mongoose = require('mongoose'); const { body, vali
.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}`);
});
如何将mongoose连接到mongodb?如果您使用createConnection,那么您应该使用连接模型()@Taymer我没有使用createConnection,我只是用我的start.js文件更新了帖子。您的
start.js
文件是否在任何地方执行?是否触发了mongoose.connection.on('connected')
?这将基本上打印打开的Mongoose连接。。。。Mongoose缓冲所有请求,直到与mongodb实例建立连接。@VictorF是的,我已经仔细检查过了。