1

Below is my Schema design

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 ]
  }
})

I want to build a query, which queries in all of the nested arrays(i.e acceptedList, requestedList, pendingList) and find out whether id is present or not and update the requestedList if id is not present in any of the list.

Any of the technique is helpful. Performance is key thing.

code.mevn
  • 155
  • 1
  • 2
  • 10

2 Answers2

0

You can use the $or operator to do that :

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

The $nin operator with [your_id] check if your id is not in the 3 arrays, you must use [] because it allows only arrays.

Nicolas
  • 457
  • 5
  • 15
  • Thanks for the answer. How to use the above query for findByIdAndUpdate()? or findById()? because i want to update a specific document based on _id of the user? – code.mevn Mar 26 '18 at 15:46
  • I don't understand what you want to do with the user's ID, you canno't join collections like in SQL, except with $lookup but I don't think you have to use it here. If you have your user's ID, pass it to the request I give you – Nicolas Mar 27 '18 at 06:46
  • Yeah, i got it. Now everything works fine. Thanks for the response. – code.mevn Mar 27 '18 at 18:28
  • I don't really understand your question. I think you can place your condition in the filter part if that can make what you want, or in the javascript part. And after in the update part, `$pull` for requestesList an `$push` to acceptedList – Nicolas Mar 28 '18 at 06:47
0

So, in your javascript code, when a user accept a request, you can use this query (you have to get the data you want to insert in acceptedList before) :

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
    }
})
Nicolas
  • 457
  • 5
  • 15