【问题标题】:Get populated data from Mongoose to the client从 Mongoose 获取填充数据到客户端
【发布时间】:2021-04-30 02:12:42
【问题描述】:

在服务器上,我正在填充用户数据,当我将其打印到控制台时一切正常,但我无法访问客户端上的数据,甚至无法访问 PlaygroundGraphQL 上的数据。

这是我的架构

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);
            }
        },
}

但在客户端甚至 Playground 中,我无法访问填充的数据。

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

我的问题是如何从客户端访问数据。

感谢您的帮助。

【问题讨论】:

    标签: javascript mongodb mongoose graphql apollo


    【解决方案1】:

    您以错误的方式使用此功能,您应该在解析器中使用您的模型名称定义一个对象,并且该对象应该包含一个通过参数值发送真实用户的方法。

    这是来自how to use this feature 的 apollo 服务器文档的完整文档

    【讨论】:

    • 我不太了解你。您是指具有填充或解析器的功能吗?我必须补充一点,除了我在填充()时没有向客户端获取数据之外,一切正常。但我可以从客户端和 Playground 访问正文..
    • 无需填充。
    • 因为你只能填充一次或两次,或者......你不知道用户想要达到多少深度这是图形部分。
    • 为了实现这部分你需要更新你的解析器。您应该只返回对象而不使用 mongoose 填充,然后在您的 resovers 中,您必须在模式中添加一个具有模型类型名称的对象。之后,您必须在其上实现一个方法,该方法根据父值返回所需的文档。检查我给你的链接以获得更好的信息,如果它再次对你没有帮助,我建议观看有关该主题的 youtube 视频
    【解决方案2】:

    像这样使用lean()

     const posts = await Post.find().populate("user").lean();
    

    【讨论】:

    • 在 Playground 上尝试 .lean() 后,它说:“errors”:[{“message”:“不能为不可为空的字段 Post.user 返回 null。”,
    • 你能在操场上跑猫鼬吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    • 2020-08-11
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多