Mongoose unique index on subdocument

后端 未结 3 388
隐瞒了意图╮
隐瞒了意图╮ 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

    Long story short: Mongo doesn't support unique indexes for subdocuments, although it allows creating them...

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 23:58

    First objectId length in mongodb must be 24. Then you can turn off _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
    
    0 讨论(0)
提交回复
热议问题