Sachin Kalsi
Sachin Kalsi

Reputation: 135

How to Delete an element from the array which is present inside an object in Mongodb/mongoose

Here is the struncture of a document of the collection 'conversations'

{
    "_id" : ObjectId("553778c0d3adab10206060db"), //conversation id
    "messages" : [
        {
            "from" : ObjectId("5530af38576214dd3553331c"),
            "_id" : ObjectId("553778c0d3adab10206060dc"),//message id
            "created" : ISODate("2015-04-22T10:32:32.056Z"),
            "read" : false,
            "message" : "second object first msg",
            "participants" : [
                ObjectId("5530af38576214dd3553331c"), //participant id
                ObjectId("553777f2d3adab10206060d8")//participant id
            ]
        },
        {
            "from" : ObjectId("5530af38576214dd3553339b"),
            "_id" : ObjectId("553778c0d3adab10206060dc"),//message id
            "created" : ISODate("2015-04-22T10:32:32.059Z"),
            "read" : false,
            "message" : "second object second msg",
            "participants" : [
                ObjectId("5530af38576214dd3553331c"),//participant id
                ObjectId("553777f2d3adab10206060d8")//participant id
            ]
        }
    ],
    "participants" : [
        ObjectId("5530af38576214dd3553331c"),
        ObjectId("553777f2d3adab10206060d8")
    ],
    "__v" : 0
}

Each document contains 'messages' array which in turn contains messages objects as array elements. Each object has participants array.

I am having conversation id , message id , participant id.

I want to delete a particular element from the 'participants' array( the 'participants' array which is present in the message object of the 'messages' array). I tried this code.

var query = { _id: mongoose.Types.ObjectId(req.conversation.id), 'messages._id':req.params.messageId};
Conversation.findOneAndUpdate(query, {$pull: {'participants' : participant_id}}, function(err, data){})

But it is deleting the object element from the outer 'participants' array. Please help me to get this done.

Thank You

Upvotes: 0

Views: 78

Answers (1)

Neo-coder
Neo-coder

Reputation: 7840

Check mongo positional operator, query as below :

db.conversations.update({
  "_id": ObjectId("553778c0d3adab10206060db"),
  "messages": {
    "$elemMatch": {
      "_id": ObjectId("553778c0d3adab10206060dc")
    }
  },
  "messages": {
    "$elemMatch": {
      "participants": {
        "$in": [ObjectId("5530af38576214dd3553331c")]
      }
    }
  }
}, {
  "$pull": {
    "messages.$.participants": {
      "$in": [ObjectId("5530af38576214dd3553331c")]
    }
  }
})

This remove given participants object from matching message array. And hope so this will help you and you should convert it into mongoose.

Upvotes: 2

Related Questions