2

i have a list schema and a question set schema. the quetsionSet schema is embedded inside the list schema. its working fine but how can i update anything inside the array of embedded document i.e. here i want to change the listname of all the documents inside questionSet (array of questionSet documents).

here is an example of my list document model

{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e"), 
"listName" : "dsa", 
"aboutList" : "dsa queestions",
 questionSet" : [ { "solved" : false, 
                   "_id" : ObjectId("60f2cc12275bbb30d8cb2695"), 
                    "topic" : "array", 
                     "name" : "array is best", 
                    "url" : "www.arr.com", 
                       "listname" : "dsa", 
                     "__v" : 0 }, 
               { "solved" : false,  
                 "_id" : ObjectId("60f2cc1b275bbb30d8cb269d"), 
                "topic" : "linked list",
               "name" : "reverse list", 
                 "url" : "www.list.com",
                "listname" : "dsa",
                 "__v" : 0 } 
               ], 
"__v" : 2 
}
DEV MEENA
  • 115
  • 6
  • Does this answer your question? [Mongoose, update values in array of objects](https://stackoverflow.com/questions/15691224/mongoose-update-values-in-array-of-objects) – Avinash Thakur Jul 17 '21 at 12:55
  • bro i tried this but it is still not updating all the documents but its just updating the first document it finds and i tried using update many but no effect – DEV MEENA Jul 17 '21 at 14:51

1 Answers1

1

you can use the following in your case

db.<collection_name>.updateOne(
    {   "_id" : ObjectId("60f2cc07275bbb30d8cb268e")},
    {
      $set: {
        'questionSet.$[].listname': "javascript"
      }
    } 
  )
Arvind Pal
  • 498
  • 3
  • 14
  • thank you bro. btw if i want to update the fields provided by form (i am using req.body and storing it in an object and removing all the fields that are left empty) so how can i update the fields which are present in the object should it be like inside $set "questionSet" : myObject or what? – DEV MEENA Jul 17 '21 at 17:01
  • Yes that shoud work, you should try and test, btw if you find the answer useful, please upvote the answer – Arvind Pal Jul 17 '21 at 17:19
  • ok thanks bro. i tried it and its working fine but if i just pass 2/3 fields it removes the 3rd field and if i pass 1 field it removes the rest 2 from the database so any fix for it? – DEV MEENA Jul 17 '21 at 17:32
  • Not clear about question, btw try google there are lot of answer there – Arvind Pal Jul 17 '21 at 17:37