1

I've been at this problem for the whole day and I just can't seem to grasp what is the problem with $pull method in MongoDB, I am trying to remove an item from my shopping cart and I always get this:

WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

I want to remove item from my array 'products' in my schema with title of BTC

My 'carts' collection data in MongoDB:

{
    "userId": {
        "$oid": "5f940f8876ad3e073a2e1e8b"
    },
    "__v": 0,
    "products": [{
        "_id": {
            "$oid": "5fc6888b1e10cd1b01382ec2"
        },
        "title": "BTC",
        "price": 10000,
        "amount": 6
    }],
    "totalPrice": 60000
}

My past 2 attempts:

db.carts.update({},
    { $pull: { "products": { title: 'BTC'} } } )
db.carts.update({ _id : '5fc6888b42d86bad7dafa319'},
    { $pull: { "products": { title: 'BTC'} } } )

Why don't I even get nMatched ?

3
  • Are you connected to the same database? Try use <db-name> Commented Dec 1, 2020 at 19:02
  • Yes I am connected to the database Commented Dec 1, 2020 at 19:08
  • Does this help? stackoverflow.com/a/62010213/2282634 Commented Dec 1, 2020 at 19:31

1 Answer 1

1

Think the problem is _id is not a string

ObjectId = require('mongodb').ObjectID;

const id = new ObjectId("idHere")
db.carts.update(
    { _id : id },
    {$pull:{ "products":{ title:'BTC' } }} 
)

And the first example won't match because it's looking for an exact match.

you can experiment here

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much, problem was that it wasn't ObjectId. Question about that, should I use ObjectId's usually or should I stick to custom String ids ?
As long as _id are produced by MongoDB i think the only way is to use ObjectID. You're welcome @Frskn
Also, you could check mongoose, it has functions prepackaged for that (and I believe mongodb driver hasnt). For example mongoosejs.com/docs/api.html#model_Model.findById (there is findByIdAndUpdate too!) @Frskn
I am using it already, thank you, I test first on terminal before testing further in express

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.