Javascript 从回调函数内部向express router发送值
当我从帖子中保存新作者时,我希望返回一条消息,说明新作者已被保存。(如果作者已经存在,我最终还想返回一些内容)我遇到的问题是,尽管作者在DB中获得了save,但我无法从author.save()的回调参数中写入res.locals.messages。(另外,请注意createAuthor是一个调用数组-我不确定这是否会使获取Javascript 从回调函数内部向express router发送值,javascript,express,mongoose,Javascript,Express,Mongoose,当我从帖子中保存新作者时,我希望返回一条消息,说明新作者已被保存。(如果作者已经存在,我最终还想返回一些内容)我遇到的问题是,尽管作者在DB中获得了save,但我无法从author.save()的回调参数中写入res.locals.messages。(另外,请注意createAuthor是一个调用数组-我不确定这是否会使获取result的值变得更加困难。) 如何将result的值传递给路由器 路线: router.post('/', authorController.createAuthor,
result
的值变得更加困难。)
如何将result
的值传递给路由器
路线:
router.post('/', authorController.createAuthor, (req, res) => {
res.json({ messages: res.locals.messages})
})
控制器:
exports.createAuthor = [
check('firstName', 'First name must be specified').isLength({min: 1}).trim(),
check('lastName', 'Last name must be specified').isLength({min: 1}).trim(),
sanitizeBody('firstName').trim().escape(),
sanitizeBody('lastName').trim().escape(),
(req, res, next) => {
const errors = validationResult(req);
var author = new Author({
firstName: req.query.firstName,
lastName: req.query.lastName
});
if (errors.isEmpty()) {
//Edit: added find before save function:
const query = {$or:[{firstName:{$regex: req.query.firstName, $options: 'i'}},
{lastName:{$regex: req.query.lastName, $options: 'i'}}]} //TODO this regex fails if a parameter is missing.
Author.findOne(query).sort([['lastName', 'ascending']]).exec((err, author) => {
if (err) {
return next(err)
}
if(!(author ==null)){
var result = {status: "Author already exists: ", author_id: String(author.id)}
res.locals.messages = result;
next();
}
});
author.save(function (err, newAuthor) {
if (err) {
return next(err)
}
var result = {status: "New author saved", author_id: String(newAuthor.id)}
res.locals.messages = result;
});
}
next();
}
];
处理保存并设置
res.locals
值后,需要调用next
:
exports.createAuthor = [
check('firstName', 'First name must be specified').isLength({min: 1}).trim(),
check('lastName', 'Last name must be specified').isLength({min: 1}).trim(),
sanitizeBody('firstName').trim().escape(),
sanitizeBody('lastName').trim().escape(),
(req, res, next) => {
const errors = validationResult(req);
var author = new Author({
firstName: req.query.firstName,
lastName: req.query.lastName
});
if (errors.isEmpty()) {
author.save(function (err, newAuthor) {
if (err) {
return next(err)
}
var result = {status: "New author saved", author_id: String(newAuthor.id)}
res.locals.messages = result;
next();
});
} else {
// Remember to do something about these non-empty errors!
next(new Error('Got more than 0 errors'));
}
}
];
另外,不要忘了处理验证错误数量不为零的情况:)使用Chris Foster的评论,我能够实现这一点:
exports.createAuthor = [
check('firstName', 'First name must be specified').isLength({min: 1}).trim(),
check('lastName', 'Last name must be specified').isLength({min: 1}).trim(),
sanitizeBody('firstName').trim().escape(),
sanitizeBody('lastName').trim().escape(),
(req, res, next) => {
const errors = validationResult(req);
var author = new Author({
firstName: req.query.firstName,
lastName: req.query.lastName
});
if (errors.isEmpty()) {
//TODO - Fix this query.
const query = {
$or: [{firstName: {$regex: req.query.firstName, $options: 'i'}},
{lastName: {$regex: req.query.lastName, $options: 'i'}}]
}
Author.findOne(query).sort([['lastName', 'ascending']]).exec((err, existingAuthor) => {
if (err) {
return next(err)
}
if (!(existingAuthor == null)) {
var result = {status: "Author already exists: ", author_id: String(existingAuthor.id)}
res.locals.messages = result;
next();
} else if (existingAuthor == null) {
author.save(function (err, newAuthor) {
if (err) {
return next(err)
}
var result = {status: "New author saved", author_id: String(newAuthor.id)}
res.locals.messages = result;
next();
});
}
});
}
}
];
谢谢你,克里斯。我添加了一个函数,在保存之前检查作者是否存在。查找的结果是
作者已存在:
但是,新作者将再次保存。如何确保新作者在确认已存在于数据库中后不会再次保存?我已尝试从“查找”中设置标志。。。请给我一秒钟时间更新我的原始代码。当调用Author.findOne(query).sort
时,它将立即转到下一个操作并执行Author.save
。之后,将调用Author.findOne(query).sort的回调,您将检查结果,但此时它已经在尝试保存新的作者了!您需要将author.save
函数放入author.findOne(query).sort
的回调函数中,并仅在结果良好时调用它。基于您最初的问题和后续代码,我认为您试图编写回调函数,但对回调的工作原理没有深入了解。在继续之前,您应该对回调进行一些研究,否则会有很多麻烦!我可以推荐。谢谢你,克里斯。我在这里做的是一种盲目的尝试,但是,我可以通过你的评论来实现这一点。我会再检查一遍。