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
陣列內獨特的子文檔。
瘋狂是怎麼字段添加到
$elemMatch
與它的運營商。謝謝你,兄弟 ! – Ryan