我正在尝试使用express node js将人名和他/她的图像添加到mongodb中,而我尝试在之前仅将文本添加到mongodb中或仅将图像添加到mongodb中,并且它们运行良好 但是当我尝试在保存帖子请求中在文本和文件之间混合时,我感到困惑,所以这是人溃败文件中的代码:
router.post('/add', (req, res) => {
const validating = personValidating(req.body);
if (validating.error) {
res.status(400).send(validating.error.details);
} else {
fileName = uuidv1(); // this to generate random name for image that I uploaded
const person = new Person({
_id: new mongoose.Types.ObjectId(),
image: req.file.image,
name: req.body.name
});
const v = person.validateSync();
if (v)
res.status(400).send('There is somthing wrong');
person.save()
.then(result => {
res.send('You have added a new person');
console.log(result);
})
.catch(err => {
res.status(401).send(err);
console.log(err);
});
}
});
,然后创建一个简单的代码,将图像同时保存到服务器中的文件夹中:
image.mv(`./public/${fileName}.png`, function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
但是如何将图像本身保存在文件夹中以及该图像在mongodb中以人名命名的路径之间合并
这也是验证的功能:
function personValidating(book) {
const personSchema = {
'image': Joi.string().required(),
'name': Joi.string().required()
}
return Joi.validate(person, personSchema);
}
这是个人模型文件中的数据库架构:
const mongoose = require('mongoose');
const personSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
image: {
type: String,
required: [true, 'Image Is Required']
},
name: {
type: String,
required: [true, 'Name Is Required']
},
});
module.exports = mongoose.model('Person', personSchema);