0

I am trying to return a nested Object that I declared in my mongoose model as follows:

const MessageSchema = new Schema({
    messageLog: [
        {
        transcript: {
            type: String
        },
        recipient: {
            type: Schema.Types.ObjectId,
            ref: 'User',
            required: true
        },
        sender: {
            type: Schema.Types.ObjectId,
            ref: 'User',
            required: true
        }
    }]
});

however I am not able to get the value for the inner object back when I try to query for it via a graphql resolver (transcript, sender, recipient are null on gql playground, but updated in db) I have set it up as follows:

query = args.messageId ? { _id: args.messageId } : { _id: new ObjectId() };

const message = await Message.findOneAndUpdate(query, {$addToSet: {messageLog: {transcript: args.messageBody, sender: args.senderId, recipient: args.recipientId}}}, {$setOnInsert: args, upsert: true, new: true, runValidators: true})
return message.messageLog;

I am able to create the new object and the nested messageLog in the db but I can only return the id for some reason as opposed to the the messageLog array of objects. Usually the issue lies in how I am resolving (resolvers) but I am going to put my typeDef here as well in case the issue lies there.

type Message {
        _id: ID
        transcript: [String]
        recipient: [User]
        sender: [User]
    }
2
  • 1
    What strikes me as odd is that your mongoose schema defines a log as an array of message, but your GraphQL schema instead defines each method property as an array. Maybe this is your issue? Commented Aug 19, 2021 at 15:29
  • @Herku the mongoose schema is an array of objects but the graphql schema is returning me the array of those values since they are not themselves defined types/schemas. Thats how I am thinking of it, and it might not be allowed that way.. Commented Aug 20, 2021 at 17:02

1 Answer 1

1

So the solution in case anyone has a similar schema setup and issue is to reference the the typeDefs with the nested levels as well. So since transcript, recipient and sender were nested a level down, the typeDef would have to be defined for the nested object and then referenced on the message type as follows:

type messageLog {
        _id: ID
        transcript: String
        recipient: User
        sender: User
    }
    type Message {
        _id: ID
        messageLog: [messageLog]
    }

and to use populate for the User since it was a schema referenced by the objectId

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.