说我有以下模式:
let personSchema = new Schema({
personData: {
image: { type: String },
basicInformation: [{
firstName: { type: String },
surname: { type: String },
email: { type: String },
phone: { type: String },
}],
}
})
如何将其保存到数据库?目前,我有一条发布路线/new
。在这种情况下,我需要一个新人来存储在数据库中:
const person = new Person({
personData: {
image: req.body.personData.file.path,
basicInformation: req.body.personData.basicInformation,
profile: req.body.personData.profile,
experience: req.body.personData.experience,
education: req.body.personData.education,
skills: req.body.personData.skills,
hobbies: req.body.personData.hobbies
}
});
问题是这一行:
image: req.body.personData.file.path,
据我所知, req.file
现在将永远是不确定的,因为文件未在req对象中定义。它在req.body对象中定义。
------------- *编辑* -------------
要求提供上传代码,因此如下:
下面的代码工作正常。为了进行测试,我从一个图像模型开始,其中仅包含一个图像字段。然后在前端,将该图像附加到FormData
并将其发送到/upload
,如下所示:
await axios.post(urlImage, formData, {
headers: {
"content-type": "multipart/form-data"
}
});
personRoutes.post('/upload', upload.single('file'), (req, res) => {
console.log('BODY: ', req.body.file)
console.log('REQ.FILE.PATH: ', req.file)
const image = new Image({
file: req.file.path,
});
image.save()
.then(result => {
console.log('YES', result)
res.redirect('/projects')
})
.catch(err => {
console.log('KUT', err)
})
});
同样,上面的代码也很好,就像一个魅力。但是,如果我想存储的不只是一个图像,例如名字,姓氏等,那该怎么办?这对我来说很棘手,因为仅将图像附加到FormData
对象上并发送就不够了不再。我必须发送一个带有image
,firstname
和lastname
字段的对象。因此,我的发布路线将类似于:
personRoutes.post('/new', (req, res) => {
const person = new Person({
personData: {
image: req.body.personData.file.path,
basicInformation: req.body.personData.basicInformation,
profile: req.body.personData.profile,
experience: req.body.personData.experience,
education: req.body.personData.education,
skills: req.body.personData.skills,
hobbies: req.body.personData.hobbies
}
});
person.save()
.then(result => {
console.log('YES', result)
res.redirect('/projects')
})
.catch(err => {
console.log('KUT', err)
})
});
在前端,我必须做这样的事情:
let testObj = {
file: this.person.personData.image,
firstname: "Reinier",
lastname: "Galien"
}
const formData2 = new FormData();
formData2.append('file', testObj)
并使用axios发送,问题是file
现在位于req.body
内部。