Mongoose unique index on subdocument

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

提交回复
热议问题