我有一个使用Express和Mongoose的NodeJS应用程序。我正在尝试编写POST路由,以便在发出对URL的POST请求(当前为/ api / v1 / forms /:formId)时,它会将变量设置为MongoDB数据库中的recipient`value。 :formID将匹配MongoDB中的_id。
到目前为止,我有:
obj[2]
我知道这对app.post("/api/v1/forms/:formId", async (req, res) => {
//TODO: Create Mailer and email templates before finalising route.
const { _name, _email, _message } = req.body;
const form = Form({
name = req.body._name,
email = req.body._email,
message = req.body._message,
recipient = Form.findById(req.params.form_id, function(err, form) {
if (err)
res.send(err);
})
});
const mailer = new Mailer(form, contactFormTemplate(form));
try {
await mailer.send();
} catch (err) {
res.status(422).send(err);
}
});
字段来说不正确,但这是我能想到的最好的事情
答案 0 :(得分:0)
按照你所做的,你可以这样做:
app.post("/api/v1/forms/:formId", async (req, res) => {
//TODO: Create Mailer and email templates before finalising route.
const { _name, _email, _message } = req.body;
let recipient;
try{
recipient = await Form.findById(req.params.form_id).exec();
} catch(err){
res.status(422).send(err);
}
const form = Form({
name: req.body._name,
email: req.body._email,
message: req.body._message,
recipient: recipient
});
const mailer = new Mailer(form, contactFormTemplate(form));
try {
await mailer.send();
} catch (err) {
res.status(422).send(err);
}
});
mongoose上的.exec()
返回一个promise,因此可以使用async / await语法。
答案 1 :(得分:0)
据我所知,这是我能想到的,
Form.findById(req.params.form_id, function(err, form) {
if (err){
res.send(err);
}else{
recipient = form.recipientValue;
}
});
答案 2 :(得分:0)
试试这个..
app.post("/api/v1/forms/:formId", async (req, res) => {
const { _name, _email, _message } = req.body;
let form;
try {
form = await Form.findById(req.params.formId).select('recipient').exec();
} catch (err) {
res.send(err);
return;
}
const nuForm = Form({
name = req.body._name,
email = req.body._email,
message = req.body._message,
recipient = form.recipient
});
try {
await new Mailer(nuForm, contactFromTemplate(nuForm)).send();
} catch(err) {
res.status(422).send(err);
}
}