skip to Main Content

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


  1. Your database already had a Profile with a user.email that is null. Since you have set that property to unique in your Schema then that’s why you get the E11000 duplicate key error.

    Now you’re wondering why you have a Profile with a user.email that is null. I suspect you have a problem with your form submission. Check to make sure the name="email" attribute is set on the <input> tag. If you are using postman to send the post request then check the spelling of the email property.

    When you try to access it here:

    email: req.body.email
    

    The value is empty so null is being set.

    Login or Signup to reply.
  2. 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 the email: "" would not be unique.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search