【问题标题】:How to return an object outside of mongoose .save().then()?如何在 mongoose .save().then() 之外返回一个对象?
【发布时间】:2019-02-20 18:48:35
【问题描述】:

我有一个 GraphQL 突变,它尝试使用 Mongoose 将对象保存到 MongoDB 集合:

Mutation: {
    addPost: (parent, args) => {
      let output = {};
      const newpost = new dbPost({
        _id: new mongoose.Types.ObjectId(),
        title: args.title,
        content: args.content,
        author: {
          id: args.authorid,
          first_name: args.authorfirstname,
          last_name: args.authorlastname,
        }
      });
      newpost.save().then((result) => {
        output = result;
      });
      return output // returns null, need result!
    },
  }

脚本工作得很好,因为它成功地将对象(通过 args 传递给它)保存到集合中。但是,我无法返回从 .then() 内部返回的对象以进行进一步处理。在 GraphiQL 中,响应是一个空对象。有什么办法,我可以在 .then() 之外返回 result 的值?

【问题讨论】:

    标签: mongodb mongoose promise graphql


    【解决方案1】:

    你可以尝试像这样使用异步等待:

      Mutation: {
          addPost: async (parent, args) => {
            let output = {};
            const newpost = new dbPost({
              _id: new mongoose.Types.ObjectId(),
              title: args.title,
              content: args.content,
              author: {
                id: args.authorid,
                first_name: args.authorfirstname,
                last_name: args.authorlastname,
              }
            });
            output = await newpost.save();
            return output 
          },
        }
    

    然后从你调用 addPost 的地方调用它:await Mutation.addPost

    【讨论】:

      【解决方案2】:

      @Mehranaz.sa answer 是正确的!

      但是 GraphQL 解析了 Promise,所以你可以简单地写这个:

      Mutation: {
          addPost: (parent, args) => {
            let output = {};
            const newpost = new dbPost({
              title: args.title,
              content: args.content,
              author: {
                id: args.authorid,
                first_name: args.authorfirstname,
                last_name: args.authorlastname,
              }
            });
            return newpost.save();
          },
        }
      

      它也很好用! PS:使用ObjectId时不需要提供_id:)

      【讨论】:

        猜你喜欢
        • 2016-07-14
        • 2015-04-14
        • 2018-04-03
        • 1970-01-01
        • 2021-05-29
        • 2014-10-29
        • 2019-05-26
        • 2015-07-18
        • 1970-01-01
        相关资源
        最近更新 更多