How to return embedded document from nested creation?



Hey guys!

Does anyone know what it would be the best way to return a created embedded document from your mutation resolver function?

For example:

createComment: async (parent, { comment }, ctx) => {
        const { postId, ...justComment } = comment;

        const updatedPost = await ctx.prisma.updatePost({
            where: { id: postId },
            data: {
                comments: {
                    create: justComment

        return updatedPost.comments[0]; // this is wrong obv


Not a solution per se but isn’t this what you want to do:

createComment: async (parent, { comment }, ctx) => {
        const { postId, ...justComment } = comment;

        const createdComment = await ctx.prisma.createComment({
            post: {
              connect: { id: postId }

        return createdComment


Hi @BenoitRanque! Thanks for the response!

I am using the Mongodb driver, and as I mentioned my document is embedded, so I can’t create a Comment directly. It needs to be created starting from a Post.


I think you need to use $fragment().


Hi @nuno thanks for your reply. I admit I don’t know to much about fragments, but I can’t see how that would help in retrieving the exact comment just created

Instead of querying all scalar fields of a model (which is the default behavior), you can specify which fields you'd like retrieve by using the $fragment

In the scenario described above I just inserted a new comment in a list of comments as an embedded document inside a post(mongodb driver).

I will receive back the entire Post with all its fields, I understand $fragment might avoid to return everything back, but it doesn’t solve the problem of how to get back the comment you just created without having to filter the comments list.

The biggest problem is that two comments could be identical, so filtering by the fields is not ideal.
I don’t know the ID.
So perhaps the only way is to filter by the most recent comment.


This topic was automatically closed 45 days after the last reply. New replies are no longer allowed.