Mongoose: unique is not working consistently

Created on 2 Mar 2019  路  5Comments  路  Source: Automattic/mongoose

I have Schema defined as:
````
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

var UsersAndRolesSchema = new Schema({
roleName: {type:String, unique:true},
userEmail: [{type:String}],
children: [{type:Schema.Types.ObjectId, ref:'UsersAndRolesSchema'}]
});

module.exports = mongoose.model('UsersAndRoles', UsersAndRolesSchema);
````

and my tests are:

let globalBefore = async function () {
    mongoose.set('useCreateIndex', true);
    await mongoose.connect('mongodb://localhost:27017/Tests', {useNewUrlParser: true});
};

let globalAfter = function () {
    mongoose.connection.close();
};

let globalAfterEach = function () {
    mongoose.connection.db.dropDatabase();
};


describe('1. addUsersAndRole', function () {

    before(globalBefore);
    afterEach(globalAfterEach);
    after(globalAfter);


    it('1.1 adds 1 valid role', function (done) {
        usersAndRolesController.addUsersAndRole('role1', ['[email protected]'], (err, userAndRole) => {
            if (err) done(err);
            else {
                assert.deepEqual(userAndRole.userEmail, ['[email protected]']);
                assert.deepEqual(userAndRole.children, []);
                assert.deepEqual(userAndRole.roleName, 'role1');
                done();
            }
        });
    });

    it('1.2 adds the same role', function (done) {
        usersAndRolesController.addUsersAndRole('role1', ['[email protected]'], (err, userAndRole) => {
            if (err) done(err);
            else usersAndRolesController.addUsersAndRole('role1', ['[email protected]'], (err, userAndRole2) => {
                if (err) done();
                else {
                    console.log(userAndRole);
                    console.log(userAndRole2);
                    done(new Error("should have failed"));
                }
            });
        });
    });
});

when I run all of test 1 I get:
1.1 pass
1.2

{ userEmail: [ '[email protected]' ],
  children: [],
  _id: 5c7a417949ad9e2588e220d0,
  roleName: 'role1',
  __v: 0 }
{ userEmail: [ '[email protected]' ],
  children: [],
  _id: 5c7a417949ad9e2588e220d1,
  roleName: 'role1',
  __v: 0 }
Error: should have failed

but when I run 1.2 alone its all good.
I cant find the reason for that.
Any help?

Most helpful comment

When you drop and recreate your database, the indexes specified in your schema need to be explicitly recreated with Model.ensureIndexes(). Since you are dropping your DB after each test, run the function before each test.

All 5 comments

When you drop and recreate your database, the indexes specified in your schema need to be explicitly recreated with Model.ensureIndexes(). Since you are dropping your DB after each test, run the function before each test.

@chidiwilliams worked. Thank you!
By the way, isn't ensureIndexes deprecated?

@omriattiya use Model.createIndexes() instead, essentially equivalent: https://mongoosejs.com/docs/api.html#model_Model.createIndexes .

Also, remember that unique is not a validator: https://mongoosejs.com/docs/validation.html#the-unique-option-is-not-a-validator

I'm not sure but I may be seeing the same issue? I erased the season collection before deploying code with unique: true as instructed and the first deploy seemed ok. The 2nd test I ended up with duplicate rows!

// make sure each user only gets one entry per season
seasonSchema.index({ owner: 1, template: 1 }, { unique: true })

image

The saving code, if relevant, is pretty simple:

playerSeason = await new Season({
        owner: data.player,
        template: currentSeason._id
      })
      await playerSeason.save()

Any advice is appreciated. I thought I was following the docs pretty accurately here.

@framerate please open up a new issue and follow the issue template

Was this page helpful?
0 / 5 - 0 ratings

Related issues

p3x-robot picture p3x-robot  路  3Comments

simonxca picture simonxca  路  3Comments

adamreisnz picture adamreisnz  路  3Comments

CodeurSauvage picture CodeurSauvage  路  3Comments

ArThoX picture ArThoX  路  3Comments