Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - Get populated data from Mongoose to the client

On the server, I am populating user-data and when I am printing it to the console everything is working fine but I am not able to access the data on the client or even on Playground of GraphQL.

This is my Schema

const { model, Schema } = require("mongoose");

const postSchema = new Schema({
    body: String,
    user: {
        type: Schema.Types.ObjectId,
        ref: "User",
    },
});

module.exports = model("Post", postSchema);
const userSchema = new Schema({
    username: String,
});

module.exports = model("User", userSchema);
const { gql } = require("apollo-server");

module.exports = gql`
    type Post {
        id: ID!
        body: String!
        user: [User]!
    }
    type User {
        id: ID!
        username: String!
    }
    type Query {
        getPosts: [Post]!
        getPost(postId: ID!): Post!
    }
`;
Query: {
        async getPosts() {
            try {
                const posts = await Post.find()
                    .populate("user");

                console.log("posts: ", posts[0]);
// This works and returns the populated user with the username

                return posts;
            } catch (err) {
                throw new Error(err);
            }
        },
}

But on the client or even in Playground, I can't access the populated data.

query getPosts {
  getPosts{
    body
    user {
       username
    }
  }
}

My question is how to access the data from the client.

Thanks for your help.

question from:https://stackoverflow.com/questions/65898893/get-populated-data-from-mongoose-to-the-client

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you are using this feature in the wrong way you should defined a Object in your resolvers with your model name and that object should contain a method that send the realated user by the parant value.

here is a full document from apollo server docs for how to use this feature


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...