Home > Enterprise >  MongoDB Duplicate Key Error With No Unique Properties?
MongoDB Duplicate Key Error With No Unique Properties?

Time:08-13

I have three schemas: Document, User, and Permission. The error I keep getting is when I add two permissions to the same user(but they belong to different documents). There error is as follows E11000 duplicate key error collection: documentor.permissions index: user_1 dup key: { user: ObjectId('62f68a84623fcef643a72f9a') } MongoServerError

I understand that this error arises when you have two of the same unique fields however it is clear that the only unique field in my schemas are the user's email in the user schema.

Here are my schemas:

const PermissionSchema = new mongoose.Schema({
    document: {
        type: mongoose.Schema.ObjectId,
        ref: "Document",
        required: [true,`Please reference a document for added permission`]
    },
    user: {
        type: mongoose.Schema.ObjectId,
        ref: "User",
        required: [true, `Please specify a user for added permission`]
    },
    access: {
        type: String,
        enum: {
            values: ["readonly", "modify", "admin"],
            message: "{VALUE} is not a valid role"
        },
        default: "readonly",
    }
});

const Permission = mongoose.model("Permission",PermissionSchema);
module.exports = Permission;

and the Document schema:

const DocumentSchema = new mongoose.Schema({

    title:{
        type: String,
        default: "No title"
    },
    author: {
        type: mongoose.Schema.ObjectId,
        required: [true, `Please specify author`],
        ref: "User"
    },
    team: {
        type: [mongoose.Schema.ObjectId],
        ref: "User",
        maxLength: [12, `Team members limited to 12`],
        default: []
    },
    content: {
        type: String
    },
},{
    timestamps: true,
    toObject: {virtuals: true},
    toJSON: {virtuals: true}
});


DocumentSchema.pre("save",function(next){
    if(!this.title)
        this.title = "No Title"
    next();
});


/* Cascade delete permissions when document is deleted. */
DocumentSchema.pre('remove', async function(next){
    await this.model("Permission").deleteMany({document: this._id});
    next();
});


DocumentSchema.virtual('permissions',{
    ref: "Permission",
    localField: "_id",
    foreignField: "document"
});

const Document = mongoose.model("Document",DocumentSchema);
module.exports = Document;

And the User schema:

const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true,` Please specify a name`],
    },
    email: {
        type: String,
        match:  /^(([^<>()[\]\\.,;:\s@\"] (\.[^<>()[\]\\.,;:\s@\"] )*)|(\". \"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9] \.) [a-zA-Z]{2,}))$/,
        required: [true, ` Please specify an email`],
        unique: true
    },
    password: {
        type: String,
        minLength: [6,` password: '{VALUE}' must be at least 6 characters`],
        required: [true, ` Must specify a password`],
        select: false
    },
    image:{
        type:String,
    }
});

const User = mongoose.model("User",UserSchema);
module.exports = User;

I would really appreciate the help and guidance.

CodePudding user response:

Drop your collection and try with new created schema it should work.

  • Related