Meteor Collection2: duplicate key error for nested uniq

129 Views Asked by At

I'm trying to make a quick script to initialize my development collections in Meteor and I found something weird.

Here is a reduced example of what I got:

    B = new SimpleSchema({
      name: { type: String, unique: true }
    })

    A = new SimpleSchema({
      name: { type: String, unique: true },
      bs: {type: [B], defaultValue: []}
    })

    As = new Mongo.Collection('as')
    As.attachSchema(A)

    As.remove({}, (e) => {
      As.insert({name: 'a_1', bs: []})
      As.insert({name: 'a_2', bs: []})
      As.insert({name: 'a_3', bs: []})
    })

When my application starts I get the following error:

MongoError: E11000 duplicate key error index: meteor.as.$c2_bs.$.name  dup key: { : null }

Checking the db I see the entries had been created and there is no B, much less one with a null name.

I reseted meteor to be sure there is no garbage but still get the same error.

Removing the uniq constraint from B schema fixes the error (but, of course, also allows me to insert invalid entries).

Is there anything I'm missing? Am I not supposed to use uniq in nested schemas?

1

There are 1 best solutions below

0
On

Ok, seems like setting the sparse key to true fix the index problem:

B = new SimpleSchema({
  name: { type: String, unique: true, sparse: true }
})

A = new SimpleSchema({
  name: { type: String, unique: true },
  bs: {type: [B], defaultValue: []}
})

I'm still not sure if this is a good practice (if I want to reutilize the B schema on an independent collection it will still use the sparse index), but I don't seem to find any better way.