我有一个带有输入字段“ firstName”,“ lastName”和“ assetTag”的表单。我想提交该表单并发布所有这些数据以及一个名为“ modelType”的附加字段。来自modelType字段的数据来自函数调用si.system(),但我不确定如何将其传递到模型中,因为这是一个承诺。
如何将数据从console.log(data.model)传递到formData?
app.js发布请求:
app.post('/', (req, res) => {
si.system()
.then(data => console.log(data.model))
.catch(error => console.error(error))
const formData = {
firstName: req.body.firstName,
lastName: req.body.lastName,
assetTag: parseInt(req.body.assetTag)
}
const system = new System(formData);
system.save()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
});
型号:
const mongoose = require('mongoose');
var SystemSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
assetTag: {
type: Number,
required: true
},
modelType: {
type: String,
required: true
}
});
module.exports = mongoose.model('System', SystemSchema);
如果您正在谈论从承诺中获得价值,则需要研究async / await。
这里是代码
app.post('/', async (req, res) => {
let data = await si.system();
const formData = {
firstName: req.body.firstName,
lastName: req.body.lastName,
modelType: data.model,
assetTag: parseInt(req.body.assetTag)
}
const system = new System(formData);
system.save()
.then(result => {
console.log(result);
})
.catch(err => {
console.log(err);
});
});