0

I am trying to update a array of objects, I need to find an element with date provided and update its entry or create a element if the date does not exist.

let us say I have an object as such

{
    "_id" : ObjectId("586358f9e2ce6f42cfc024d7"),
    "gid" : "10",
    "entries" : [ 
        {
            "date" : 20161228,
            "_id" : ObjectId("586358f9e2ce6f42cfc024d8"),
            "entry" : [ 
                "fwaf", 
                "afwaaf", 
            ]
        }
    ],
    "__v" : 0
}

and in this query the entry is shown as undefined(shown in console because of mongoose debug option)

Entry.findOneAndUpdate({'entries.date':20161228},{'entry':['inputis','a']},{upsert:true},function(err,data){
              if (err) console.error(err)
              console.log(data);
              return res.json(data)
            })

entries.entry does not work either. I followed this [Update nested array with Mongoose - MongoDB But I think it is not possible for me to use subdocuments, Should I restructure my database or is it fine if I keep it as such.

how can i reference the found object in mongoose? so that i can update its array?

Community
  • 1
  • 1
Bharat
  • 287
  • 1
  • 5
  • 14

2 Answers2

0

It will be entries.entry

Entry.findOneAndUpdate({'entries.date':20161228},{'entries.entry':['inputis','a']},{upsert:true},function(err,data){
              if (err) console.error(err)
              console.log(data);
              return res.json(data)
            })
Simran
  • 2,364
  • 1
  • 12
  • 19
  • As I mentioned in the question, entries.entry will not work, it throws an error saying "message: 'cannot use the part (entries of entries.entry) to traverse the element" – Bharat Dec 28 '16 at 09:12
0

You forgot to specify the array element index. Try this:

Entry.findOneAndUpdate({'entries.date':20161228},{$set: {"entries.0.entry":["inputis","a"]}},{upsert:true},function(err,data){
              if (err) console.error(err)
              console.log(data);
              return res.json(data)
            })

this will update the first element of entries array. To update all elements of entries array, use

{$set: {"entries.$.entry":["inputis","a"]}}
felix
  • 9,007
  • 7
  • 41
  • 62