Mongoose unique index on subdocument

后端 未结 3 387
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 23:01

Let\'s say I have a simple schema:

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


        
3条回答
  •  囚心锁ツ
    2020-12-15 23:46

    This comes up in google so I thought I'd add an alternative to using an index to achieve unique key constraint like functionality in subdocuments, hope that's OK.

    I'm not terribly familiar with Mongoose so it's just a mongo console update:

    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 documents looking like:

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

    The key being that you ensure update will not return a document to update (i.e. the find part) if your subdocument key already exists.

提交回复
热议问题