【发布时间】:2023-03-03 05:28:19
【问题描述】:
我的 Apollo 变异函数获取 2 个文件数组作为参数。然后我将它写入文件系统,将它们的位置推送到数组中。之后,我希望将数组写入 MongoDB,但由于异步,mongo 有空字段。 我该如何处理?
const { createWriteStream } = require("fs");
const path = require('path');
const Post = require('../../models/Post');
const checkAuth = require('../../utils/check-auth');
module.exports = {
Mutation: {
async addPost(_, { postInput: { title, description, pictures, panoramas, price, location } }, ctx) {
const anon = checkAuth(ctx);
let pics = [];
let pans = [];
pictures.map(async (el) => {
const { createReadStream, filename } = await el;
await new Promise(res =>
createReadStream()
.pipe(createWriteStream(path.join("static/images", filename)))
.on("close", res)
);
pics.push(`static/images/, ${filename}`);
})
panoramas.map(async (el) => {
const { createReadStream, filename } = await el;
await new Promise(res =>
createReadStream()
.pipe(createWriteStream(path.join("static/images", filename)))
.on("close", res)
);
pans.push(path.join("static/images", filename));
})
const newPost = new Post({
title,
description,
price,
pictures: pics,
panoramas: pans,
createdAt: new Date().toISOString(),
userId: anon.id,
location,
});
const res = await newPost.save();
console.log(res)
return true;
}
}
}
【问题讨论】:
标签: node.js mongodb express asynchronous apollo