2

I know the question is duplicate but I dont know Why I am stuck

Question:

How can I edit "requirement.$.update" array documents, using find by _id and requirement.update._id (and if needed requirement._id )

// edit version number level2
  exports.editVersionNumberPost = function(req, res){ 
    var query = {
            date: req.body.date,
            number: req.body.number,
            description: req.body.description 
        }
    Project.findOneAndUpdate({ name:  req.params.name, 
                               "requirement._id" : req.params.versionID, 
                               "requirement.update._id" : req.params.versionNumID},  
        {"$set": 
            {"requirement.$.update" :  query 
        }   
        },  { new: true }, 
        function(err, obj){})
 };

my Schema

----------------
    namr: String
    requirement:[{
        version: Number,
        update:[{
            date: Date,
            number: Number,
            description: String
        }]
    }],
--------
6
  • 2
    Well explained here Commented May 13, 2019 at 11:23
  • @AnthonyWinzlet Still coudnt find a solution , Do you have time to check this ? Commented May 13, 2019 at 13:01
  • What issue you are facing? Please update your question with some explanation and what is not working for you. Commented May 13, 2019 at 13:03
  • Updated, please check now @AnthonyWinzlet Commented May 13, 2019 at 13:12
  • 1
    Hmm. Yet another person pointed to an existing answer ( link in first comment ) who did not read beyond the first block of code. If you actually read it, then that "first block" actually comes with the explanation that using a hard index value, is not how to do it. The other resounding message other than the MongoDB 3.6 available solution is that nested arrays are a really bad idea. I suggest actually reading the content rather than just looking for code to "cargo cult". You might learn something useful. Also please don't comment with "please help" on answers to others questions. Commented May 14, 2019 at 11:34

1 Answer 1

5

You can use below query

db.getCollection("test").updateOne(
  { "name":  req.params.name },
  { "$set": { "requirement.$[outer].update.$[inner].number": 100000 } },
  {
    "arrayFilters": [
      { "outer._id": mongoose.Types.ObjectId(req.params.versionID) },
      { "inner._id": mongoose.Types.ObjectId(req.params.versionNumID) }
    ]
  }
)
Sign up to request clarification or add additional context in comments.

2 Comments

Can we add another level too? like 1-outer, 2-inner, 3-other
@BinaraMedawatta Please ask a new question if you have further doubts

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.