2016-12-24 7 views
1

私はuserSchemaにidと友人の配列を含んでいます。友人の配列は、実際には、ID、性別、および名前を保持する別のスキーマの配列です。つまり、SubDocumentsの配列です。サブ文書を含む配列のaddToSet相当

var attributesSchema = new Schema({ 

    id: String, 
    gender: String, 
    name: String 

}) 

var userSchema = new Schema({ 

    id: { 
     type: String, 
     unique: true, 
     required: true 
    }, 

    Friends: [attributes] 

}); 

前に、私はFriendsStringのアレイに等しく持っていました。 AddToSetは、異なる文字列値を持たない限り、Friends配列に何かを追加しないので、問題なく動作します。しかし、サブ文書では、残念ながら、addToSetは何かが重複しているかどうかを判断することはできません。

次られたサブ文書を複製しないで私の試み:

明らか
User.update({ 
    id: req.body.userId 
}, { 
    $addToSet: { 
     Friends: { 
      id: req.body.friendId, 
      gender: req.body.gender, 
      name: req.body.name 
     } 
    } 
}); 

、これは動作しませんし、私はFriends配列内のユニークなサブ文書を追加する方法を探しています。

答えて

1

あなたは要素サブ文書要素一致していないときに、実際に更新する$not$elemMatchを使用することができます。

User.update({ 
    "id": req.body.userId, 
    "Friends": { 
     "$not": { 
      "$elemMatch": { 
       "id": req.body.friendId 
      } 
     } 
    } 
}, { 
    $addToSet: { 
     Friends: { 
      "id": req.body.friendId, 
      "gender": req.body.gender, 
      "name": req.body.name 
     } 
    } 
}); 

を使用すると、他の重複条件

+0

を持っている場合は、$elemMatchにフィールドを追加することができます柔軟モンゴがどのようにクレイジーその演算子と一緒に。ありがとう、男! – Ryan

関連する問題