【发布时间】:2021-08-14 22:17:30
【问题描述】:
我有一个像这样的视频架构:
const videoSchema = new mongoose.Schema({
cover: { // image url
type: String,
required: true,
},
category: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Category'
}],
})
当我创建新视频时,我将从第三个站点获取封面图片并将其保存到 AWS S3,然后更新新的封面网址。我有这样的预存中间件
videoSchema.pre("save", async function save(next) {
try {
await transferImagesToS3(this.cover, async (err, resp) => {
if (err) {
next()
}
if (resp.Location) { // image uploaded to AWS S3 and return new image url here
this.cover = resp.Location // I set new url here
next()
}
})
} catch (err) {
next(err)
}
})
传输图像功能
// transfer image to S3
export const transferImagesToS3 = (imgURL, filename, callback) => {
request({
url: imgURL,
encoding: null
}, function (err, res, body) {
if (err) return callback(err, res);
s3.upload({
Bucket: 'mybucket',
Key: `public/images/${filename}.jpeg`,
cacheControl: 'max-age=604800',
ContentType: res.headers['content-type'],
ContentLength: res.headers['content-length'],
Body: body // buffer
}, callback)
})
}
以上代码,this.cover 是来自第三个网站的图片网址。图片上传成功,但预保存未更新新图片网址。这段代码有什么问题?你能帮帮我吗?
谢谢
【问题讨论】:
-
它显示了我想要的新 URL,但我不知道为什么在 DB 中,它没有更新。
-
是的,它是展示视频文件。只是没有保存到数据库中。
标签: javascript node.js mongodb mongoose