Mongoose unique subdocument index

Say I have a simple circuit:

var testSchema = new mongoose.Schema({ map: { type: [ mongoose.Schema.Types.Mixed ], default: [] }, ...possibly something else }); 

Now make sure that the pairs ( _id , map._id ) are unique.

 testSchema.index({ _id: 1, 'map._id': 1 }, { unique: true }); 

A quick check with db.test.getIndexes() shows that it was created.

 { "v" : 1, "unique" : true, "key" : { "_id" : 1, "map._id" : 1 }, "name" : "_id_1_map._id_1", "ns" : "test.test", "background" : true, "safe" : null } 

The problem is that this index is ignored, and I can easily create multiple subdocuments with the same map._id . I can execute the following query several times:

 db.maps.update({ _id: ObjectId("some valid id") }, { $push: { map: { '_id': 'asd' } } }); 

and in the end we get the following:

 { "_id": ObjectId("some valid id"), "map": [ { "_id": "asd" }, { "_id": "asd" }, { "_id": "asd" } ] } 

What's going on here? Why can I click on conflicting subdocuments?

+7
indexing mongodb mongoose
source share
3 answers

In short: Mongo does not support unique indexes for subdocuments, although it does allow you to create them ...

+15
source share

This appears on google, so I thought I'd add an alternative to using an index to achieve a unique key constraint, such as functionality in subdocuments, hopefully OK.

I am not very familiar with Mongoose, so this is just updating the mongo console:

 var foo = { _id: 'some value' }; //Your new subdoc here db.yourCollection.update( { '_id': 'your query here', 'myArray._id': { '$ne': foo._id } }, { '$push': { myArray: { foo } }) 

With similar documents:

 { _id: '...', myArray: [{_id:'your schema here'}, {...}, ...] } 

The key that you provide the update will not return the updated document (for example, part of the search) if your subdocument key already exists.

+11
source share

The first object length in mongodb should be 24. Then you can disable _id and rename _id as id or others, and try $ addToSet , Good luck.

CoffeeScript Example:

 FromSchema = new Schema( source: { type: String, trim: true } version: String { _id: false }//to trun off _id ) VisitorSchema = new Schema( id: { type: String, unique: true, trim: true } uids: [ { type: Number, unique: true} ] from: [ FromSchema ] ) //to update Visitor.findOneAndUpdate( { id: idfa } { $addToSet: { uids: uid, from: { source: source, version: version } } } { upsert: true } (err, visitor) -> //do stuff 
-3
source share

All Articles