Updating a Nested Array with MongoDB

前端 未结 2 1169
滥情空心
滥情空心 2020-11-21 05:18

I am trying to update a value in the nested array but can\'t get it to work.

My object is like this

 {
    \"_id\": {
        \"$oid\": \"1\"
    },
         


        
2条回答
  •  感动是毒
    2020-11-21 06:07

    I know this is a very old question, but I just struggled with this problem myself, and found, what I believe to be, a better answer.

    A way to solve this problem is to use Sub-Documents. This is done by nesting schemas within your schemas

    MainSchema = new mongoose.Schema({
       array1: [Array1Schema]
    })
    
    Array1Schema = new mongoose.Schema({
       array2: [Array2Schema]
    })
    
    Array2Schema = new mongoose.Schema({
       answeredBy": [...]
    })
    

    This way the object will look like the one you show, but now each array are filled with sub-documents. This makes it possible to dot your way into the sub-document you want. Instead of using a .update you then use a .find or .findOne to get the document you want to update.

    Main.findOne((
        {
            _id: 1
        }
    )
    .exec(
        function(err, result){
            result.array1.id(12).array2.id(123).answeredBy.push('success')
            result.save(function(err){
                console.log(result)
            });
        }
    )
    

    Haven't used the .push() function this way myself, so the syntax might not be right, but I have used both .set() and .remove(), and both works perfectly fine.

提交回复
热议问题