2016-12-24 31 views
1

我有一個userSchema,其中包含一個id和一組朋友。朋友數組實際上是一個包含id,gender和name的另一個模式的數組,因此是一個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] 

}); 

之前,我曾經有Friends等於的String陣列。 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

相關問題