Search code examples
javascriptarraysmongodbmongoosesubdocument

Mongoose - findOneAndUpdate dynamically $push into array


I am trying to dynamically add new values into an array field.

Been making enough progress lately to not have to bother asking them on here although this is one question I thought should indeed be asked! So to start it off here's my schema:

  var ugh = new mongoose.Schema({
    yes: String,
    bio: String,
    keys: [{ 
      nickname: String,
      data1: String,
      data2: Boolean,
      data3: String,
      data4: String,
    }]
  });

  var ughhh = mongoose.model('X', ugh, 'x');

and here is the resolver I am trying to write to solve:

      setSomething: async (root, { nickname, data1, data2, data3, data4 }, { userId }) => {
        if (nickname) {
        let action = await ughhh.findOneAndUpdate(
          { _id: userId }, 
          { $set: 
            { 
              'keys.0.nickname': nickname, 
              'keys.0.data1': data1,
              'keys.0.data2': data2,  
              'keys.0.data3': data3,
              'keys.0.data4': data4,
            },
          }, 
          {
          new: true,
          upsert: true,
        });
        action;
        }
        return null;
      },
    },

Now I do like the numerical sorting of newly set keys, starting with 0.

But when I try to $set another, it replaces the value instead of adding the new entry into the array!

How can I add new entries into the array instead of replacing the current value and I prefer adding new entries with unique ID or key for future reference


Solution

  • you can just push into the array field like:

     { $push: 
          keys: { 
              'nickname': nickname, 
               'data1': data1,
               'data2': data2,  
               'data3': data3,
               'data4': data4
           }
       }
    

    note that when you push new items into the array, it would generate an unique '_id' field which is useful for future reference