0

I have a MongoDB document that looks like this:

"_id": ObjectID(48kf4kblahblahblah),
"name": "A Person's Name",
"username":  "apersonsemail@mail.com",
"password":  "a hashed password",
"formulas":  [
               {
                 "f_id": ObjectID(4k8s9blahblahblah),
                 "name": "A Name",
                 "description": "A description",
                 "ingredients": [{object}, {object}]
               }
             ]
}

I'm trying to query for a document based on _id and then remove the sub-document from the formulas array based on an item's f_id value using $pull.

However, it's not updating anything.

This is taking part in an Express/Node application, and my code looks like this:

router.delete('/formula-list/:index', function(req, res){
  var db = req.db.collection('users');
  var index = req.params.index;
  db.updateOne({"_id": new ObjectID(req.user.id)}, { $pull: {"formulas": {"f_id": index}} }, function(err, r){
             assert.equal(null, err);
             assert.equal(1, r.modifiedCount);
             req.db.close();
           });
  res.end();
});

And I get Assertion Error: 1 == 0

I've consoled req.params.index and I get the value

59683b480986823e10f39fba

And if I console the r object the matchedCount is 1, so I know it's finding the document as well. It's just not doing anything with it.

My questions seems very similar to this one, with the exception that I'm not looking to delete multiple items, but I don't see how this would affect the results of my query.

Thank you.

Jonathan Bechtel
  • 3,497
  • 4
  • 43
  • 73
  • 1
    Is this mongoose or the core node driver? If it's the latter you need to cast to `ObjectId`, otherwise things do not match and nothing gets done. I'm guessing it's "core" since you use `ObjectId` on the primary `_id`. So you need to change the `$pull` as well `{ $pull: { "formulas": { "f_id": ObjectID(index) } } }` – Neil Lunn Jul 14 '17 at 04:04
  • @NeilLunn - Yes, this was it. If you put this as an answer I'll mark it complete. – Jonathan Bechtel Jul 14 '17 at 04:09
  • I was trying remove array index with pull as using php.. but it was not removed... cuz of condition element was integer so i cast int and it removed – Ucdemir Jun 26 '19 at 10:43

0 Answers0