1

I am trying to remove an object form an array based on the name(Ticker) of an object. Others have also asked this question and I have tried many of their solutions but I just cant get it to work. It never actually performs the task of removing anything.

Here is my schema:

{
    _id : 1234 
    email : [email protected] 
    pass : password  
    stock : [ 
        {
        Ticker : TSLA 
        Market : Nasdaq 
        Notes : [ 
            "Buy at 700", 
            "Sell at 1000"
            ] 
        },
        {
        Ticker : AAPL 
        Market : Nasdaq 
        Notes : [ 
            "Buy at 110", 
            "Sell at 140"
            ] 
        },
    
    ]
}

Here is what I currently have, but I've also tried a few other combinations of commands:

router.post(`/watchlist/remove/:email/:pass/:stock`, (req, res) => {
    var email = req.params.email
    var pass = req.params.pass
    var tempStock = req.params.stock


    userModel.findOneAndUpdate({ email: email  }, { $pull : {'stock.Ticker' : tempStock} }   , (documents, err) => {
        if (err) {
            res.send(err);
        }
        else {
            res.send(documents)
        }
    })
})

2 Answers 2

1

I think this might help

userModel.findOneAndUpdate({ email: email  }, { $pull:{stock:{Ticker : tempStock}}}, (documents, err) => {
        if (err) {
            res.send(err);
        }
        else {
            res.send(documents)
        }
    })

Also you might want to double-check if you are receiving value in tempStock variable

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

1 Comment

I didn't realize earlier but the tempStock was receiving an object and not just a string. Thanks for the help your code worked once I sorted tempStock out.
0

Your query should be like this:

userModel.findOneAndUpdate({
    "email": email,
    "stock.Ticker": tempStock
}, {
    "$pull": {
        "stock": {
            "Ticker": tempStock
        }
    }
}, (documents, err) => {
    if (err) {
        res.send(err);
    }
    else {
        res.send(documents)
    }
})

Comments

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.