如何返回猫鼬.save()。then()之外的对象?

时间:2018-09-16 19:25:11

标签: mongodb mongoose promise graphql

我有一个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 的值吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

@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:)