Sunday, 30 April 2017

findByIdAndUpdate in Mongoose gives duplicate key error

I have a mongoose model that is defined as follows:

import mongoose from 'mongoose';

const eventSchema = new mongoose.Schema({
    _id: {type: Number, required: true},
    uuid: {type: String, required: true},
    data: {type: Object, required: true},
    organisers: [String],
    volunteers: [String],
    participants: [String],
    mentors: [String]
});


export default mongoose.model('Event', eventSchema);

Now, I am trying to update the organisers section here as such:

import Event from '../models/event-model';
function addUserToEventOrganisers(userId, eventId) {
    Event.findByIdAndUpdate(
        eventId,
        {$addToSet: {organisers: userId}},
        {safe: true, upsert: true},
        function (err) {
            if (err) {
                console.log(err);
            }
        }
    );
}

However, when I try to do this, I get an exception and my entire document gets reset and has only the organisers field. Here is the exception:

(eventId passed was 15)

{ [MongoError: E11000 duplicate key error collection: appdb.events index: id dup key: { : 15 }] name: 'MongoError', message: 'E11000 duplicate key error collection: appdb.events index: id dup key: { : 15 }', driver: true, code: 11000, index: 0, errmsg: 'E11000 duplicate key error collection: appdb.events index: id dup key: { : 15 }', getOperation: [Function], toJSON: [Function],
toString: [Function] }

I have no clue why this is happening. Could someone help?



via Solly

No comments:

Post a Comment