Home > Mobile >  Unable to insert data into db where a collection has a relationship
Unable to insert data into db where a collection has a relationship

Time:01-09

This is in a Node project where I am trying to write a graphql api for a simple blog.
I am using apollo and behind the scenes attempting to save data to a mongo db via mongoose.

I am currently getting the following error when I try to save a Post data.

"GraphQLError: ID cannot represent value: { type: "Buffer", data: [Array] }", "at GraphQLScalarType.serialize (/Users/name/projects/graphtime/node_modules/graphql/type/scalars.js:301:11)",

It is complaining about the Author insertion as part of the Post I believe.

Is there something wrong with my schema or how I am performing the query on the Apollo GraphiEditor?

The is the DB Schema

import mongoose from "mongoose";

const authorSchema = new mongoose.Schema({
  name: { type: String, required: true },
  avatar: { type: String },
});

export const Author = mongoose.model('Author', authorSchema);

const postSchema = new mongoose.Schema({
  title: { type: String, required: true },
  authors: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Author'
    }
  ]
});

export const Post = mongoose.model('Post', postSchema);

This is the graphql Schema

type Post {
    id: ID!
    title: String
    authors: [Author]
}

type Author {
    id: ID!
    name: String
    avatar: String
}

type Mutation {
    addPost(
        title: String!,
        authors: [ID!],
    ): Post
}

This is the grapql resolver.

const resolvers = {
  Mutation: {
    addPost: (_, args, context) => {
      const newPost = new Post({
        title: args.title,
        authors: args.authors,
      });
      return newPost.save();
    },
  },
};

This is how I am querying in the editor which throws the error.
P.S: The DB already has an existing author in there and lets say the id for that row is: 63babc44e18d174016b03433

mutation {
  addPost(
    title: "New Post",
    authors: ["63babc44e18d174016b03433"],
  ) {
    title
    authors {
      id
      name
    }
  }
}

CodePudding user response:

You have defined the mutation in this way:

type Mutation {
    addPost(
        title: String!,
        authors: [ID!],
    ): Post
}

That's mean addPost return a Post object, which is:

type Post {
    id: ID!
    title: String
    authors: [Author]
}

So authors is an array of Authors objects, not the _ids.

You are getting the ID and saving into DB but the returned object does not match [Author]. Also note how the postSchema is mongoose.Schema.Types.ObjectId. Referenced to Authors, yes, but is an array of IDs.

So you can return an array of IDs instead the Author object or populate the query in mongoose because you have the reference.

  • Related