Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 文件数组';异步操作后,Mongodb中的链接为空_Node.js_Mongodb_Express_Asynchronous_Apollo - Fatal编程技术网

Node.js 文件数组';异步操作后,Mongodb中的链接为空

Node.js 文件数组';异步操作后,Mongodb中的链接为空,node.js,mongodb,express,asynchronous,apollo,Node.js,Mongodb,Express,Asynchronous,Apollo,我的Apollo变异函数获取两个文件数组作为参数。然后我将其写入文件系统,将它们的位置推送到阵列中。之后,我希望用MongoDB编写数组,但由于异步,mongo有空字段。 我怎么办 const { createWriteStream } = require("fs"); const path = require('path'); const Post = require('../../models/Post'); const checkAuth = require('../../utils/ch

我的Apollo变异函数获取两个文件数组作为参数。然后我将其写入文件系统,将它们的位置推送到阵列中。之后,我希望用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;
    }
  }
}

您应该等到所有承诺都得到解决,然后再创建一个新文档

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;
}

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

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

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;
}
这是一个快速的例子,我建议您稍微清理一下,并添加一些错误处理