Reputation: 4694
I have the following schema
var customerSchema = new Schema({
customerID: String,
phoneNumber: String
})
customerSchema.path('customerID').validate(function (customerID, next) {
Customer.findOne({customerID: customerID}, function (err, user) {
if (err) {
return next(false);
}
if (!user) {
return next(true); //Valid
} else {
return next(false);
}
});
}, 'customerID Already Exists');
This works perfectly when I was trying to add the same customerID. It will not let me. But previously I tried to press the ADD button at the same time on different computer. Somehow the same customerID gets added.
How to prevent such edge cases from happening? I am using MongoLab. Does the latency present a big problem?
Upvotes: 0
Views: 58
Reputation: 57212
It's very possible to have this type of behavior:
Press add button on computer1
Press add button on computer2
Validation occurs for the first add and the customer does not exist
Validation occurs for the second add BEFORE the first insert is done and the customer does not yet exist
Both adds succeed
You can put a unique constraint on the field at the database level to prevent this - https://docs.mongodb.org/v3.0/tutorial/create-a-unique-index/
Depending on your needs, you can also have an "upsert" that updates or inserts a new record. In your case, if you're concerned about two users creating a new user with the same ID, just put an index on it at the database.
Upvotes: 1