ipalibowhyte
ipalibowhyte

Reputation: 1563

How do you delete a Json object by id in node Mongodb?

i have a Mongodb collection named "EVENTS" and in the collection i have an object of array which looks like this:

{
   "Events":[
      {
         "_id":"53ae59883d0e63aa77f7b5b2",
         "Title":"Title Blank",
         "Desc":"Description Blank",
         "Date":"2014-06-04 00:30",
         "Link":"http://googleparty.com",
         "Event":"Victoria Centre",
         "dateCreated":"28/6/2014  06:58"
      },
      {
         "_id":"53ae59883d0e63aa77f7b5b3",
         "Title":"Hello World",
         "Desc":"hello",
         "Date":"2014-06-04 00:30",
         "Link":"http://linkedinparty.com",
         "Event":"social",
         "dateCreated":"30/2/2014  11:10"
      }
   ]
}

how would i delete an object by id in node.js so " delete(53ae59883d0e63aa77f7b5b2)" will yield this:

{
       "Events":[
           {
         "_id":"53ae59883d0e63aa77f7b5b3",
         "Title":"Hello World",
         "Desc":"hello",
         "Date":"2014-06-04 00:30",
         "Link":"http://linkedinparty.com",
         "Event":"social",
         "dateCreated":"30/2/2014  11:10"
          }
       ]
    }

Regards

Upvotes: 0

Views: 1196

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151112

If all you really want to do is "empty" the array then you just need to use the $set operator with an .update() and "set" the array as an empty one:

db.collection.update({},{ "$set": { "Events": [] } },{ "mutli": true})

So the .update() operation takes a "query" to select the documents in your collection, a blank query as shown selects everything. The "update" section contains the $set operation that just replaces the current "Events" field with an empty array.

The "multi" option there makes sure this is applied to every document that matches. The default is false and will only update the first document that matches.

For more specific operations removing selected array elements, look at the $pull operator. Your edit shows now that this is what you want to do:

db.collection.update(
    { "Events._id": ObjectId("53ae59883d0e63aa77f7b5b2") },
    { "$pull": { "Events": { "_id": ObjectId("53ae59883d0e63aa77f7b5b2") } } }
)

But your inclusion of arrays with _id fields seems to indicate that you are using mongoose, so the ObjectId values are cast automatically:

Model.update(
    { "Events._id": "53ae59883d0e63aa77f7b5b2" },
    { "$pull": { "Events": { "_id": "53ae59883d0e63aa77f7b5b2" } } },
    function(err,numAffected) {

    }
);

Upvotes: 2

Related Questions