我想在我的单个帖子上显示成功消息。我正在使用connect-flash,express-session显示Flash消息。
也试图在其他页面中刷新消息。但是,该消息不是强制性的。因此,它不会显示在任何页面上。我正在按scotch显示成功消息。
[当我尝试提交空白表格时,它在控制台MongoError: E11000 duplicate key error collection
中显示以下错误
模式:
const eventSchema = new Schema({
name: {
type: String,
require: [true, 'Event name is required']
},
slug: {
type: String,
unique: true,
sparse: true
},
description: {
type: String,
require: [true, 'Event description is required']
},
}, {collection: 'event'});
const eventModel = mongoose.model('Event', eventSchema);
app.js:
const session = require('express-session'),
flash = require('connect-flash');
app.use(session({
secret: 'secret-key',
cookie: {
secure: true,
maxAge: 60000,
},
resave: false,
saveUninitialized: false
}));
app.use(flash());app.use(session({
secret: 'secret-key',
cookie: {
secure: true,
maxAge: 60000,
},
resave: false,
saveUninitialized: false
}));
app.use(flash());
控制器:
const Event = require('../models/event'),
{ body, validationResult } = require('express-validator');
exports.showSingleEvent = async(req, res) => {
try {
await Event.findOne({ slug: req.params.slug }).exec((error, event) => {
if(error) {
res.status(404);
res.send('Events not found');
}
res.render('pages/single', {
title: `Event: ${event.name}`,
event: event,
success: req.flash('success')
});
});
} catch (error) {
return next(error);
}
};
exports.createEvent = ([
// Validate data
body('name')
.isLength({ min: 5, max: 30 })
.not().isEmpty()
.trim()
.escape(),
body('description')
.isLength({ min: 5, max: 200 }).withMessage('Must be between 5 & 200')
.not().isEmpty()
.trim()
.escape()
], async(req, res) => {
// Check if has errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
const event = new Event({
name: req.body.name,
description: req.body.description
});
await event.save((error) => {
if(error) throw error;
// Flash successful message
req.flash('success', 'Data has created successfully!');
// Redirect to newly created event
res.redirect(`/events/${event.slug}`);
});
}
});
single.ejs:
<% if (success.length > 0) { %>
<div class="alert alert-success mt-2 mb-2">
<%= success %>
</div>
<% } %>
<div class="jumbotron text-center">
<h1><%= event.name %></h1>
<p><%= event.description %></p>
<p>
<a href="/events" class="btn btn-success">All events</a>
</p>
</div>
create.ejs:
<% if (errors.length > 0) { %>
<div class="alert alert-success mt-2 mb-2">
<% for (error of errors ) { %>
<%= error %> <br>
<% } %>
</div>
<% } %>
<form action="/events/create" method="POST">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label>Description</label>
<textarea name="description" rows="5" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg">Create</button>
</div>
</form>
此错误的原因是。您尝试在其中插入的集合中没有索引。因此,解决方案是删除该集合并再次运行您的程序。