快递MDN教程 此处 使用以下代码从pug.body.genre中提取复选框的值。
从主代码来看,req.body.genre应该从表单中返回一个选择值的数组,如下所示。
div.form-group
label Genre:
div
for genre in genres
div(style='display: inline; padding-right:10px;')
input.checkbox-input(type='checkbox', name='genre', id=genre._id, value=genre._id, checked=genre.checked )
label(for=genre._id) #{genre.name}
button.btn.btn-primary(type='submit') Submit
当req.body.genre在下面的代码部分被引用到创建新图书模型实例的最后中间件函数中时,它只返回存储为字符串的第一个值。因此,即使在表单中勾选了多个复选框,genre 字段最终也总是只保存一个值。
exports.book_create_post = [
// Convert the genre to an array.
(req, res, next) => {
if(!(req.body.genre instanceof Array)){
if(typeof req.body.genre==='undefined')
req.body.genre=[];
else
req.body.genre=new Array(req.body.genre);
}
next();
},
// Validate fields.
body('title', 'Title must not be empty.').isLength({ min: 1 }).trim(),
body('author', 'Author must not be empty.').isLength({ min: 1 }).trim(),
body('summary', 'Summary must not be empty.').isLength({ min: 1 }).trim(),
body('isbn', 'ISBN must not be empty').isLength({ min: 1 }).trim(),
// Sanitize fields.
sanitizeBody('*').escape(),
sanitizeBody('genre.*').escape(),
// Process request after validation and sanitization.
(req, res, next) => {
// Extract the validation errors from a request.
const errors = validationResult(req);
// Create a Book object with escaped and trimmed data.
var book = new Book(
{ title: req.body.title,
author: req.body.author,
summary: req.body.summary,
isbn: req.body.isbn,
genre: req.body.genre
});
类型字段已被定义为存储一个值的数组。
var BookSchema = new Schema(
{
title: {type: String, required: true},
author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
summary: {type: String, required: true},
isbn: {type: String, required: true},
genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
}
);
我应该怎么做才能得到req.body.genre作为一个选择值的数组?
我找到了罪魁祸首
Express验证器的这一行代码造成了这个问题。
sanitizeBody('*').escape()
代之以
sanitizeBody('author').escape(),
sanitizeBody('title').escape(),
sanitizeBody('isbn').escape(),
sanitizeBody('summary').escape(),
sanitizeBody('genre.*').escape(),
现在一切都正常了,数组现在通过req体传递。