如何解决从 Mongoose 获取填充数据到客户端
在服务器上,我正在填充用户数据,当我将其打印到控制台时一切正常,但我无法访问客户端上的数据,甚至无法访问 Playground
的 GraphQL
}}。
这是我的架构
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
}
}
}
我的问题是如何从客户端访问数据。
感谢您的帮助。
解决方法
您以错误的方式使用此功能,您应该在解析器中使用您的模型名称定义一个对象,并且该对象应该包含一个通过父值发送相关用户的方法。
这里是 how to use this feature 的 apollo 服务器文档的完整文档
,像这样使用lean()
:
const posts = await Post.find().populate("user").lean();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。