Mongoose中postalCode的unique:false不生效问题求助
postalCode (Even When Marked Non-Unique in Mongoose) Hey there, let's break down what's going on here:
Your Mongoose schema explicitly sets postalCode to unique: false, but the error message E11000 duplicate key error index: yorkdale.users.$postalCode_1 dup key tells us the real issue: there's already a unique index on the postalCode field in your mLab database collection. Mongoose schema settings don't automatically remove existing database indexes once they've been created—so even if you updated the schema later, that old unique index is still enforcing uniqueness on postal codes.
Fix Steps:
1. Delete the Unwanted Unique Index in mLab
Head over to your mLab account, navigate to your yorkdale database and users collection:
- Go to the Indexes tab for the collection
- Look for the index named
postalCode_1(it should be marked as "Unique") - Click the delete option to remove this index
2. Verify Your Schema Configuration
Your existing schema code for postalCode is already correct, but double-check to make sure it stays this way:
postalCode:{ type: String, required: [true, 'Postal Code is required'], unique: false },
3. Optional: Sync Indexes (Dev Environment Only)
If you want Mongoose to automatically manage indexes during development, add autoIndex: true to your database connection (don't use this in production—manual index management is safer):
mongoose.connect(yourDatabaseUrl, { useNewUrlParser: true, useUnifiedTopology: true, autoIndex: true // Enable only for development });
4. Improve Error Messaging (Better User Experience)
Right now your error message only mentions email duplicates, which is misleading when the issue is postal code. Update your POST route to handle duplicate key errors properly:
app.post('/join', function(req,res){ var myData = new User(req.body); myData.save().then(item => { res.send("Information saved to database"); }).catch(err => { if (err.code === 11000) { const duplicateField = Object.keys(err.keyPattern)[0]; let errorMsg; if (duplicateField === 'Email') { errorMsg = "Error! Email already used! Please go back and try again"; } else { errorMsg = `Error! ${duplicateField.charAt(0).toUpperCase() + duplicateField.slice(1)} already exists! Please go back and try again`; } res.status(400).send(errorMsg); } else { res.status(400).send("Error! Unable to save to database. Please check your input and try again"); } }); });
内容的提问来源于stack exchange,提问作者Workkkkk

