0

I have a MongoDB document that looks like this:

"_id": ObjectID(48kf4kblahblahblah),
"name": "A Person's Name",
"username":  "[email protected]",
"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.

3
  • 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) } } } Commented Jul 14, 2017 at 4:04
  • @NeilLunn - Yes, this was it. If you put this as an answer I'll mark it complete. Commented Jul 14, 2017 at 4: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 Commented Jun 26, 2019 at 10:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.