Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongooseJS cant disable unique to field

Tags:

mongoose

This is my mongoosejs schema. I set name unique to false, but this is what i get: MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: testdb1.images.$name_1 dup key: { : "aaa" }

imageSchema = new Schema({
    url: {
        type: String,
        unique: true,
        required: true
    },

    category: {
        type: String,
        required: true
    },

    vote: {
        type: Number,
        required: true
    },

    name: {
        type: String,
        unique: false,
        required: true
    },

    voteArray: [],
    favorite: false,
    tags: []

});

any ides how to solve this ? suggestions ?

like image 703
nobody_cares_ Avatar asked May 16 '14 13:05

nobody_cares_


People also ask

Why mongoose doesn't check unique field?

1. Duplicate documents already created in DB before defining this property You might have already added some duplicate data in the database so mongoose and MongoDB simply doesn't check unique field because it's already messed up Delete the messed data from the MongoDB collections page to solve it 2.

How do I make email unique in mongoose?

One workaround is to make the email property required, which disallows null and undefined: If you need email to be unique unless it is not defined, you can instead define a sparse unique index on email as shown below. To make MongoDB E11000 error messages user-friendly, you should use the mongoose-beautiful-unique-validation plugin.

What is the difference between dropdatabase () and deletemany () in mongoose?

When writing Mongoose tests, we normally recommend using deleteMany () to clear out data in between tests, rather than dropDatabase (). This ensures that you delete all documents, without clearing out database-level configuration, like indexes and collations. deleteMany () is also much faster than dropDatabase ().


1 Answers

Mongoose won't modify existing indexes, so you'll need to drop that index in the MongoDB shell and then let Mongoose recreate it using the definition in your schema:

> db.images.dropIndex('name_1');
like image 76
JohnnyHK Avatar answered Sep 21 '22 11:09

JohnnyHK