如何将多个文件上载到谷歌云存储+;Node.js?
我在Node.JS后端工作,我基本上需要做以下基本工作:如何将多个文件上载到谷歌云存储+;Node.js?,node.js,express,asynchronous,file-upload,google-cloud-storage,Node.js,Express,Asynchronous,File Upload,Google Cloud Storage,我在Node.JS后端工作,我基本上需要做以下基本工作: 将多个文件保存到Google云存储 将GCS公共URL数组保存到MongoDB 将“post”数据与公共URL数组一起保存到Mongo DB 这是我的密码。最后它工作了,保存了Mongo DB中的所有东西,但看起来很混乱。如何修复这些代码行 model/Post.js: const mongoose = require('mongoose'); const {Schema} = mongoose; const postSchema =
const mongoose = require('mongoose');
const {Schema} = mongoose;
const postSchema = new Schema({
title: {type: String},
subtitle: {type: String},
description: {type: String},
imagesUrl: [{type: String}],
_user: {
type: Schema.Types.ObjectId,
ref: 'User',
},
});
const Post = mongoose.model('Post', postSchema, 'posts');
module.exports = {
Post,
};
控制器/postController.js
const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucket = storage.bucket(process.env.GCLOUD_STORAGE_BUCKET);
//Func to save data into Mongo DB
const createPost = async (data) => {
try {
const post = await new Post({
title: data.title,
subtitle: data.subtitle,
description: data.description,
_user: data.userId,
});
await _.map(data.imagesUrl, (value, key) => {
post.imagesUrl.push(value);
});
post.save();
const userById = await User.findOne({_id: data.userId});
userById._posts.push(post);
await userById.save();
return post;
} catch (e) {
return e.stack;
}
};
//Func to upload files to GCS
const uploadFileTGcs = async (file) => {
let promises = [];
_.forEach(file, (value, key) => {
const {originalname, buffer} = value;
const blob = bucket.file(originalname.replace(/ /g, '_'));
const promise = new Promise((resolve, reject) => {
const blobStream = blob.createWriteStream({
resumable: false,
public: true,
});
blobStream.on('error', () => {
reject(`Unable to upload image, something went wrong`);
}).on('finish', async () => {
const publicUrl = format(
`https://storage.googleapis.com/${bucket.name}/${blob.name}`,
);
resolve(publicUrl);
}).end(buffer);
});
promises.push(promise);
});
const urls = Promise.all(promises).then(promises => {
return promises;
});
return urls;
};
routes/postRoute.js
router.post('/create', async (req, res, next) => {
try {
if (!req.files) {
res.status(400).json({
messages: 'No file uploaded',
});
return;
}
const imagesUrl = await postsController.uploadFileTGcs(req.files);
const postCreated = await postsController.createPost({
title: req.body.title,
subtitle: req.body.subtitle,
description: req.body.description,
imagesUrl: imagesUrl,
userId: req.user._id,
});
res.status(postCreated ? 200 : 404).json({
result: postCreated,
message: 'Post created',
});
} catch (e) {
res.status(500).json({
result: e.toString(),
});
}
});