如何实现GraphQL禁止重复邮箱提交?解决同版本GraphQL下重复邮箱无报错问题
Hey there! The issue here is that your current mutation saves the client directly to the database without checking for existing emails, and your database model doesn’t have a constraint to block duplicates either. Let’s fix this with two key, reliable steps:
1. Enforce Uniqueness at the Database Level
First, add a unique constraint to your Client model—this creates a safety net that prevents duplicates even if someone tries to add a client outside your GraphQL API (like direct database edits).
Assuming you’re using Mongoose (common with GraphQL + MongoDB), update your schema to mark the email field as unique:
const mongoose = require('mongoose'); const ClientSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, required: true, unique: true // This tells the database to reject duplicate emails }, phone: { type: String, required: true } }); module.exports = mongoose.model('Client', ClientSchema);
Now the database will throw a duplicate key error if you attempt to save a client with an existing email.
2. Add Pre-Save Validation in Your Resolver
While the database constraint works, checking for duplicates before saving gives users a clearer, more user-friendly error message instead of a generic database error. Update your mutation’s resolve function with this check (using async/await for cleaner code):
name:'Mutation', fields: { addClient: { type: ClientType, args: { name: {type: GraphQLNonNull(GraphQLString)}, email: {type: GraphQLNonNull(GraphQLString)}, phone: {type: GraphQLNonNull(GraphQLString)}, }, resolve: async (parent, args) => { // Check if a client with this email already exists const existingClient = await Client.findOne({ email: args.email }); if (existingClient) { throw new Error(`A client with email ${args.email} is already registered!`); } // Create and save the new client if no duplicates are found const client = new Client({ name: args.name, email: args.email, phone: args.phone }); return client.save(); } } }
Why the Tutorial Worked but Yours Didn’t
Chances are the tutorial’s Client model already had the unique: true constraint on the email field. When the presenter tried to save a duplicate, the database threw an error that GraphQL passed back as a mutation error. Without that constraint, your database simply allows duplicate entries.
By combining both steps, you get a robust solution: the database constraint acts as a last line of defense, and the resolver check provides immediate, clear feedback to users.
内容的提问来源于stack exchange,提问作者Süleyman Eminbəyli

