简体   繁体   中英

Updating nested array mongodb

I think there are multiple ways to do this, and that has me a little confused as to why I can't get it to work.

I have a schema and I would like to update Notes within it but I can't seem to do it. Additionally, if I want to return the notes how would I go about doing it?

schema:

{
    _id : 1234 
    email : me@me.com 
    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"
            ] 
        },
    
    ]
}

Each user has a list of stocks, and each stock has a list of notes.

Here is what I have tried in order to add a note to the list.

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


    userModel.findOne({email: email} , (err, documents)=>{
        if (err){
            res.send(err); 
        }
        else if (documents === null){
            res.send('user not found'); 
        }else if (bcrypt.compareSync(pass , documents.pass)){
            userModel.findOneAndUpdate({email : email , "stock.Ticker" : tempStock}, {$push :  {Notes : note}} ,(documents , err)=>{
                if(err){
                    res.send(err);
                }else {
                    res.send(documents.stock);
                }
            })
          
        }
    })
  

})

Thanks:)

Currently, you are pushing the new note into a newly created Notes property inside the model instead of into the Notes of the concrete stock . I am not completely aware of the mongoose semantics but you need something like this:

userModel.findOneAndUpdate({ email: email, "stock.Ticker": tempStock }, { $push: { "stock.$.Notes": note } }, (documents, err) => {

$ gives you a reference to the currently matched element from the stock array.

For the second part, I am not sure what you mean by

Additionally, if I want to return the notes how would I go about doing it?

They should be returned by default if you're not doing any projection excluding them.

Also, as per the docs(and general practise), the callback for the findOneAndUpdate has a signature of

(error, doc) => { }

instead of

(documents, err) => { }

so you should handle that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM