我知道如果我尝试调用的字段为空,我会收到此错误,但是当我创建电子邮件时,该电子邮件的 ID 确实会保存在用户中。但是当我尝试使用以下查询查询该用户时
query all {
users{
sentEmail{
sender
emailbody
recipient
}
}
}
}
我收到错误“不能为不可为空的字段 User.sentEmail 返回 null。” 如果 sentEmail 中有 id,为什么我会收到此错误
解析器
const { Email, User } = require('../models')
const resolvers = {
Query : {
users : async () => {
return await User.find({}).populate('emails');
},
emails : async (parent, { email }) => {
const params = email ? { email } : {};
return await Email.find(params).sort({ sentDate: -1 });
},
},
Mutation : {
addemail : async (parent, {sender, recipient, subject, emailbody}) => {
const newemail = await Email.create({ sender, recipient, subject, emailbody});
await User.findOneAndUpdate(
{ email: newemail.sender },
{ $addToSet : { sentEmails: newemail._id }}
)
await User.findOneAndUpdate(
{ email: newemail.recipient },
{ $addToSet : { receivedEmails: newemail._id }}
)
return newemail
},
addUser: async (parent, { firstName , lastName , email, password }) => {
const user = await User.create({ firstName , lastName , email, password }, {new: true})
},
}
};
module.exports = resolvers
类型定义
const { gql } = require('apollo-server-express');
const typeDefs = gql`
type User {
_id : ID
firstName : String
lastName : String
email : String
password : String
sentEmail: [Email]!
}
type Email {
_id : ID
sender : String
recipient : String
emailbody : String
sentDate : String
}
type Query {
users : [User]
emails(email: String) : [Email]
}
type Mutation {
addemail(sender: String!, recipient: String!, subject: String , emailbody: String!): Email
addUser(firstName: String!, lastName: String!, email: String!, password: String! ): User
}
`;
module.exports = typeDefs;