0

我知道如果我尝试调用的字段为空,我会收到此错误,但是当我创建电子邮件时,该电子邮件的 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;

4

1 回答 1

0

请检查您从解析器的回复。似乎它将 sentEmail 字段的值返回为 null 或您的响应 json 中不存在 sentEmail 字段。

于 2022-01-30T12:10:21.133 回答