Search code examples
node.jsmongodbmongooseerror-handlingmongoose-schema

MongoError: E11000 when trying to update a user


So I have a node app where users can register an account (username, email, pw, icon image) to use the site. I created a profile page with a link to an Edit Form to edit/update your username, email, and icon image. However, whenever I try to update a user's info, I get a MongoError.

This doesn't happen consistently. Sometimes it successfully updates, so I don't know what is causing the issue.

Here is the github link to my code: https://github.com/P4sc4l94/yelp-camp

My User schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');

const UserSchema = new Schema({
  email: {
    type: String,
    required: true,
    unique: true
  },
  image: {
    type: String
  }
});

My User controller that is trying to update info:

module.exports.editProfile = async (req, res, next) => {
  const {id} = req.params;
  const {username} = req.body.user;
  const {email} = req.body.user;
  const {image} = req.body.user
  console.log(id)
  console.log(username)
  console.log(email)
  console.log(image)
  const user = await User.findOneAndUpdate(id, {username, email, image}, {
    new: true
  });
  user.save();

  console.log(user);
  req.logout();
  req.flash('success', 'Successfully updated profile!')
  return res.redirect(`/login`);
};

Solution

  • E11000 is a "duplicate key error" meaning that you cannot do "new" on the record, you could use new and upsert if you were querying for something other than the id

    you should be doing await user.save() when its used, but there is no reason to be doing it here

    you should also be casting your id as a document ID if you are using mongodb ID's, which i presume you are as a safety precaution

    const mongoose = require('mongoose')
    const { ObjectId } = mongoose.Types
    const { id } = req.params
    const user = await User.findOneAndUpdate({ _id: new ObjectId(id) }, { username, email, image });