1

for the following structure, I am trying to update the first array item under options to be ["milk", 1]:

{    
  options:[["milk", 0],
           ["chocolate", 0],
           ["others", 0]],
  timestamp:"2017-09-26T14:42:49.359Z"
  title:"shopping list"
  username:"a"
}

this is the mongoose snippet I use.

router.put('/',(req,res) => {
  let {_id, value, option} = req.body;   
  eventModel.findOneAndUpdate(    
    {_id:_id, options: [option, value]},
    { $set: {"options.$": [option, value + 1]}},
      function(err){
      if(err){
          res.status(400).json({ error: err });
      }
      console.log("event updated");
  });    
});

I always get the "event updated" with no errors but the item does not get updated, any help is appreciated. Thank you

1

1 Answer 1

1

Why do you use this kind of array pairs to store your values ? Any specific reason.

Otherwise you could store the data like this, and then query:

const ShoppingListSchema = new Schema({
  username: {type: String},
  title: {type: String},
  timestamp: {type: Date, default: Date.now()},
  options: [{
    product: {type: String},
    selected: {type: Number}
  }]
});
  // then
  eventModel.findOneAndUpdate(    
    {_id:_id, 'options.product': productName, 'options.selected': selected},
    {"options.$.value": value + 1},
      function(err){
      if(err){
          res.status(400).json({ error: err });
      }
      console.log("event updated");
  }); 

// also, quick note. If you want set items in your list as "included" or not, then...you dont actually need the "value" part. Product is in the shopping list, if it is in the array.

options: ["milk", "bread", "beer"] would work just as well

also, i can see you are doing "value + 1" Just a quick note, there is an operand for incrementing values:

$inc: {field: value}

Quick update with an alternative option:

db.getCollection('list').update({"options": ["milk", 0]}, {$set: {"options.$.1": 1} })

use $.1 to refer to the second element in your array, which is the number.
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer @. honestly, the whole schema is not optimal, but if I change it at this point, I need to do a lot of refactoring. so I was wondering if there is a way to update the data as the way they are.
just wanted to tag @user:1932379

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.