Mongoose: How to ensure index has been created in case of uniqueness error

Created on 4 Aug 2020  路  4Comments  路  Source: Automattic/mongoose

Mongoose version 5.9.26

Hello there,

Consider the following code:

'use strict';

const _ = require('lodash');
const assert = require('assert');
const Promise = require('bluebird');
const mongoose = require('mongoose');
mongoose.Promise = Promise;

require('mongoose').set('debug', true);

// DB
let connect = mongoose.connect('mongodb://localhost:27018/test', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

const UserSchema = new mongoose.Schema({
  slug: {
    type: String,
  },
});

UserSchema.index({slug: 1}, {unique: true});

const User = mongoose.model('User', UserSchema);

// Create test data
connect.then(async () => {
  mongoose.connection.db.dropDatabase();

  await User.create({
    slug: 'test',
  });

  await User.collection.dropIndexes();

  // Allowed to create duplicate data, we just dropped the index. This is for demonstration purposes.
  await User.create({
    slug: 'test',
  });

  // Now let's try to restore the index.

  await User.syncIndexes({background: false});
  await User.ensureIndexes({background: false});
  await User.createIndexes({background: false});
  await User.collection.createIndex({slug: 1}, {unique: true});
});

Only the last call to direct mongodb "correctly" fails and rejects with the expected E11000 duplicate key error dup key, syncIndexes, ensureIndexes and createIndexes do _not_ create the index, because it probably errors silently.

Is there a way to make these function reject with the error? I feel this should be expected behavior.

Also, https://mongoosejs.com/docs/api/model.html#model_Model.syncIndexes shows the following code

await Customer.createIndex({ age: 1 }); // Index is not in schema

But createIndex is not a mongoose function.

confirmed-bug

Most helpful comment

That's a bug, we made it so that syncIndexes() correctly rejects with the first error that it encounters when building indexes.

All 4 comments

That's a bug, we made it so that syncIndexes() correctly rejects with the first error that it encounters when building indexes.

Thank you!

Should I create another issue for

Also, https://mongoosejs.com/docs/api/model.html#model_Model.syncIndexes shows the following code

await Customer.createIndex({ age: 1 }); // Index is not in schema

But createIndex is not a mongoose function.

?

@saveman71 yes please, sorry we missed that

Was this page helpful?
0 / 5 - 0 ratings