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
        }]
    }],
--------
ShibinRagh
  • 6,530
  • 4
  • 35
  • 57
  • 2
    Well explained [here](https://stackoverflow.com/questions/23577123/updating-a-nested-array-with-mongodb) – Ashh May 13 '19 at 11:23
  • @AnthonyWinzlet Still coudnt find a solution , Do you have time to check this ? – ShibinRagh May 13 '19 at 13:01
  • What issue you are facing? Please update your question with some explanation and what is not working for you. – Ashh May 13 '19 at 13:03
  • Updated, please check now @AnthonyWinzlet – ShibinRagh May 13 '19 at 13:12
  • and please I do not prefer using "index" value to the target – ShibinRagh May 13 '19 at 13:14
  • 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. – Neil Lunn May 14 '19 at 11:34

1 Answers1

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) }
    ]
  }
)
Ashh
  • 44,693
  • 14
  • 105
  • 132