1

下面是我的架构设计

const Schema1 = mongoose.Schema({
      _id: false,
      id: { type: mongoose.Schema.Types.ObjectId,
        ref: 'UserinfoSchema' 
      },
      name: { type: String , default: null },
      from: { type: Date, default: Date.now }
})

const ProfileSchema = mongoose.Schema({
  profilename:{
    type: String,
    required: true
  },
  list:{
    acceptedList:[ Schema1 ],
    requestedList:[ Schema1 ],
    pendingList:[ Schema1 ]
  }
})

我想构建一个查询,它查询所有嵌套数组(即acceptedList、requestList、pendingList)并找出id是否存在,如果id不存在于任何列表中,则更新requestList。

任何技术都是有帮助的。性能是关键。

4

2 回答 2

0

您可以使用$or运算符来做到这一点:

db.Collection.update({
    $or: {
        "list.acceptedList": {$nin: [your_id]},
        "list.requestedList": {$nin: [your_id]},
        "list.pendingList": {$nin: [your_id]}
    }
}, {
    $addToSet: {
        "list.requestedList": your_id
    }   
});

带有 [your_id]的$nin运算符检查您的 id 是否不在 3 个数组中,您必须使用 [] 因为它只允许数组。

于 2018-03-26T09:41:18.550 回答
0

因此,在您的 javascript 代码中,当用户接受请求时,您可以使用此查询(您必须先获取要插入到接受列表中的数据):

db.Collection.update({
    _id: collection_id,
    "list.requestedList": request_id
}, {
    $pull: {
        "list.requestedList": your_id // I re use what i give to you
    },
    $addToSet: {
        "list.acceptedList": your_id // or what you want
    }
})
于 2018-03-28T08:21:25.090 回答