The main issue is my code saves the first time around but then will not work no matter what I try. It should be simple to save to the database and it is the first time but after that the database refuses to save the data. I do not believe this is an issue of validation but rather something with the save method.
I am expecting the profile database to add another profile. However it only does this for the first profile added. After that it always produces some error. I have tried different post requests, i have tried deleting all elements in the database.
I am given the following error:
Profile not created
MongoServerError: E11000 duplicate key error collection: test.profiles index: email_1 dup key: { email: null }
.../message_stream.js:33:9) at writeOrBuffer (internal/streams/writable.js:358:12) {
index: 0,
code: 11000,
keyPattern: { email: 1 },
keyValue: { email: null },
[Symbol(errorLabels)]: Set(0) {}
}
I am trying to save a profile to MongoDB database using mongoose with the following code:
// create new profile
router.post('/create', async (req, res) => {
const profile = new Profile({
user: {
username: req.body.username,
email: req.body.email,
password: req.body.password1,
},
trips: [],
});
try {
const prof1 = await profile.save();
console.log(`created profile ${profile.user.username}`);
console.log(req.params);
return res.json(prof1);
} catch (err) {
console.log("Profile not created");
console.log(err)
return res.send(err);
}
});
Here is my profile Schema:
const profileSchema = new Schema({
user: {
username: {
type: String,
required: [true, "Add a username"],
unique: true,
},
email: {
type: String,
required: [true, "Add an email"],
unique: true,
},
password: {
type: String,
required: [true, "Add a password"],
},
},
trips: [{
type: Schema.Types.ObjectId,
ref: "Trip",
}],
}, {timestamps: true});
2
Answers
Your database already had a
Profile
with auser.email
that isnull
. Since you have set that property tounique
in your Schema then that’s why you get theE11000 duplicate key error
.Now you’re wondering why you have a
Profile
with auser.email
that isnull
. I suspect you have a problem with your form submission. Check to make sure thename="email"
attribute is set on the<input>
tag. If you are using postman to send the post request then check the spelling of theemail
property.When you try to access it here:
The value is empty so
null
is being set.You didn’t show enough of the data you’re passing into the POST body but I’m assuming you resent the same request twice.
the constraints used in your
email
property are likely failing uniqueness.If you pass an empty string for
email
, the next time you add it again will cause it to fail because theemail: ""
would not be unique.