Meteor mongo unique index

Hello everybody
I would like that in a collection a field can only receive unique values. so :

BqeTypeOpe =new Mongo.Collection('bqetypeope',{idGeneration: 'MONGO',
    schema:{
        "opbType_nom":          {type:String, index:1, unique:true}, // type d'opération
        "opbType_libelle":      {type:String}           // libelle de l'opération
    }
});

When I make an insert in the collection, this check does not work and I end up with “opbType_nom” having the same value
In Meteor I add the following packages:
session
iron:dynamic-template
maazalik:malihu-jquery-custom-scrollbar
gadicohen:headers
aldeed:collection2@3.0.0
aldeed:schema-index
mrt:jquery-easing

Can someone tell me what I missed?
Thank you for your answers
YC

https://docs.mongodb.com/manual/core/index-unique/

You’ll likely need to work on the database directly, most likely with:

Have you attached the schema to the collection?

Yes, I did that:

BqeTypeOpe =new Mongo.Collection('bqetypeope',{idGeneration: 'MONGO',
    schema:{
        "opbType_nom":          {type:String, index:1, unique:true}, // type d'opération
        "opbType_libelle":      {type:String}                        // libelle de l'opération
    }
});

and I do:

BqeTypeOpe.insert({'opbType_nom':codeOpe,'opbType_libelle':libOpe},function(error,id){
        if(error){...... }
        else {....}
    });

Should we change something?

You’re not using the packages correctly. You have to create a collection, create a schema and then use Collection.attachSchema to attach the schema to the collection…

const BqeTypeOpe = new Mongo.Collection('bqetypeope', { idGeneration: 'MONGO' });

const Schema = new SimpleSchema({
    "opbType_nom": { type: String, index: 1, unique: true }, // type d'opération
    "opbType_libelle": { type: String }                        // libelle de l'opération
});

BqeTypeOpe.attachSchema(Schema);

Code is king when you need help with an issue. I can’t assume your issue is caused by the same thing as @yvancoyaud

Ok, I changed and did as you told me, and now I have the following error :
ReferenceError: SimpleSchema is not defined

and yet I added the package $ meteor add aldeed:simple-shema
my file .meteor/local/packages :

session
iron:dynamic-template
maazalik:malihu-jquery-custom-scrollbar
gadicohen:headers
aldeed:collection2@3.0.0
aldeed:simple-schema
mrt:jquery-easing

Where is the problem ?

You’ve gotta import it.

OK, I forgot, excuse …:blush:
Now everything is OK
thanks a lot for your help

YC

1 Like