这是我的架构:
type User {
_id: ID!
username: String
email: String!
firstName: String
lastName: String
avatar: String
createdAt: Date!
updatedAt: Date!
}
type Tweet {
_id: ID!
text: String!
user: User!
favoriteCount: Int!
createdAt: Date!
updatedAt: Date!
}
这是我的Tweet
模型:
import mongoose, { Schema } from 'mongoose';
const TweetSchema = new Schema({
text: {
type: String,
minLength: [5, 'Your tweet is too short.'],
maxLength: [144, 'Your tweet is too long.']
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
favoriteCount: {
type: Number,
default: 0
}
}, { timestamps: true });
export default mongoose.model('Tweet', TweetSchema);
上述GraphQL架构的表达方式如下:
import { graphqlExpress } from 'apollo-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import typeDefs from '../graphql/schema';
import resolvers from '../graphql/resolvers';
const schema = makeExecutableSchema({
typeDefs,
resolvers
});
const app = express();
app.use(
'/graphql',
graphqlExpress(req => ({
schema
}))
);
我使用以下代码模拟一些用户和使用faker的推文:
https://pastebin.com/raw/kJ9m8KjR
当整个事情运行时,我可以看到mongodb中填充了与这样的用户链接的虚拟推文:
但是当我通过GraphiQL查询时,用户信息不会通过:
有什么想法吗?
答案 0 :(得分:1)
你的解析器得到这样的推文:
Tweet.find({}).sort({ createdAt: -1 });
如果您查看docs,您会注意到需要告诉mongoose使用populate将id引用替换为实际文档:
Tweet.find({}).populate('user').sort({ createdAt: -1 });