我在Apollo graphql中具有Post Comment模型的实现,哪种模式是我想知道哪种实现是正确的?
type Post {
id: ID!
title: String
image: File
imagePublicId: String
comments: [Comment] # we have type for Comment in another schema file
createdAt: String
updatedAt: String
}
extend type Query {
# Gets post by id
getPosts(authUserId: ID!,skip: Int,limit: Int): Post
}
我有一个解析器,它通过猫鼬的填充函数(如下所示)来解析Post类型并解析评论:
const Query = {
getPosts: async (root,{ authUserId,skip,limit },{ Post }) => {
const allPosts = await Post.find(query)
.populate({
path: 'comments',options: { sort: { createdAt: 'desc' } },populate: { path: 'author' },})
.skip(skip)
.limit(limit)
.sort({ createdAt: 'desc' });
return allPosts
}
}
在解析器中实现getPosts查询的第二种方式的可能方法是不使用猫鼬的填充函数,而通过为其编写单独的函数来手动解析它:
const Query = {
getPosts: async (root,{ Post }) => {
const allPosts = await Post.find(query)
.skip(skip)
.limit(limit)
.sort({ createdAt: 'desc' });
return allPosts
}
Post: {
comments: (root,args,ctx,info) => {
return Comment.find({post: root._id}).exec()
}
}
}