【问题标题】:Array of files' links is empty in Mongodb after asynchronous operations异步操作后,MongoDB 中的文件链接数组为空
【发布时间】: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


    【解决方案1】:

    你应该等到所有的承诺都解决了,然后才继续创建一个新文档。

    async function addPost(_, {postInput: {title, description, pictures, panoramas, price, location}}, ctx) {
        const anon = checkAuth(ctx);
        let pans = [];
        let pics = [];
    
        pictures.map(async (el) => {
            pics.push(
                new Promise(async (resolve, reject) => {
                    const {createReadStream, filename} = await el;
    
                    await new Promise(res =>
                        createReadStream()
                            .pipe(createWriteStream(path.join("static/images", filename)))
                            .on("close", res)
                    );
                    resolve(`static/images/, ${filename}`);
                })
            )
        });
    
        await Promise.all(pics);
    
        panoramas.map(async (el) => {
            pans.push(
                new Promise(async (resolve, reject) => {
                    const {createReadStream, filename} = await el;
    
                    await new Promise(res =>
                        createReadStream()
                            .pipe(createWriteStream(path.join("static/images", filename)))
                            .on("close", res)
                    );
                    resolve(path.join("static/images", filename));
                }));
        });
    
        await Promise.all(pans);
    
        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;
    }
    

    这是一个简单的示例,我建议您稍微清理一下并添加某种错误处理。

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 2019-04-01
      • 1970-01-01
      • 2020-02-16
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2018-06-04
      相关资源
      最近更新 更多