1

Based on my code below, I am looking to set a variable to the req.body.update. I can't figure out how to accomplish this. When I set it to queryz nothing happens.

I am using mongoose for this.

app.put('/application/todoupdate/:id/:index', function(req, res, next) {
    console.log('accessed put route');
    let item = 0;
    let queryz = "todos." + item + ".todoText";
    console.log(queryz);
    User.where({_id: req.params.id}).update({
      $set: {
        "todos.0.todoText": req.body.update
        // queryz: req.body.update
      }
    }).then(
      res.send(req.body.update)
    )
  });

My data base stucture is:

{
"_id": {
    "$oid": "77777777777"
},
"todos": [
    {
        "todoText": "req success",
        "timestamp": "7777777777777"
    },
    {
        "todoText": "something",
        "timestamp": "7777777777777"
    }
]
}

What I came to was which allowed me to access the lower level:

app.put('/application/todoupdate/:id/:timestamp', function(req, res, next) {
    console.log('accessed put route');
    User.where({_id: req.params.id, "todos.timestamp": 
req.params.timestamp}).update({
      $set: {
        "todos.$.todoText": req.body.update
      }
    }).then(
      res.send(req.body.update)
    )
  });
Ashh
  • 44,693
  • 14
  • 105
  • 132
Josh Bowden
  • 892
  • 3
  • 12
  • 28

1 Answers1

0

You need to use positional operator to update nested array of objects

User.update(
    { _id: req.params.id }, 
    { "$set": { "todos.$.todoText": "hello" } }
)

and if you want to update all objects in array then you can use $[] positional operator

User.update(
    { _id: req.params.id }, 
    { "$set": { "todos.$[].todoText": "hello" } }
)
Ashh
  • 44,693
  • 14
  • 105
  • 132
  • So how do I place a variable in that? I have no problem specifically stating what I want to update but if I pass an index as I did in the params how do I place that as the position. – Josh Bowden Jun 13 '18 at 20:25
  • You got me like 90% of the way there thanks man! – Josh Bowden Jun 13 '18 at 20:45