最近,我试图通过异步过程将许多HTML表单值附加到MongoDB数据库
这个const createproperty是我在数组中获取的MongoDB字段
const createProperty = ['propertyType',
'propertyName',
'bhkType',
'ownershipType',
'builtUpArea',
'propertyAge',
'floorType',
'floorNumber',
'numberOfFloors',
'city',
'expectedPrice',
]
..这些ID是我放入数组中的HTML表单中的一些ID
const myids = ['#thisPropertyType',
'#thisPropertyName',
'#thisBhk',
'#thisOwnerShip',
"#thisArea",
'#thisAge',
'#thisFloor',
'#thisFloorNo',
'#thisTotalFloor',
'#thisCity',
'#thisEp', ]
这个新属性将为我提供Html表单中的值,所有值都以数组的形式存储,并且此for循环可以很好地工作,这为我提供了所有表单值
const newProperty = new Array();
for(var i=0;i<myids.length;i++){
newProperty[i] = $(myids[i]).val();
}
const form = new FormData();
for(var i=0;i<newProperty.length;i++){
form.append(createProperty[i],newProperty[i]);
}
await createData(form);
这是异步过程之后的功能
export const createData = async (data) => {
try{
for (var value of data.values()) {
console.log(value);
}
const res = await axios({
method: 'POST',
url: '/api/v1/myapi',
data
});
if(res.data.status==='success'){
alert('success');
}
console.log(data);
}
catch(err){
alert('error');
}
}
我在console.log中记录了createdata函数的值,它为我提供了完美的值,但是当我查看集合时,没有将这些值推送到mongodb服务器,有一个文档被创建但其中没有数据..
请帮助我我做错了什么,我不明白我做错了什么..
非常感谢您对我的帮助!
axios期望数据不是JSON对象FormData
这将使用createProperty
数组中的键将主体构造为JSON
const data = {};
myids.forEach((id, index) => {
data[createProperty[index]] = $(myids[i]).val();
})
那么您可以直接通过以下方式发送这些值 axios
await createData(data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句