0

I want to push element inside the nested object. I am not getting any error but record is not updating.

{ 
    "_id" : ObjectId("5aa589b31b79fbe3312d3a1b"), 
    "settings" : {
        "clientSetting" : [
            "Hello1",
             "Hello2",
        ], 
        "adminSetting" : [
            "Hello1",
             "Hello2",
        ], 
    }
}

Modal declarations:-

import mongoose from 'mongoose';

const { Schema } = mongoose;

const settingSchema = new Schema(
  {
    settings: {
      clientSetting: [
        { type: String },
      ],
      adminSetting: [
        { type: String },
      ],
    },
  },
  { collection: 'mySettings' },
);

export default mongoose.model('MySetting', settingSchema, 'mySettings');

Here is what I tired

export const update = (req, res) => {

    MySetting.find((err, globalSettings) => {
     MySetting.update(
         { _id: mongoose.Types.ObjectId(globalSettings[0]._id) },
         { $push: { 'settings.$.clientSetting': { type: req.body.value } } },);
      });
}

here I want to push { type: req.body.value } into clientSetting.

Sagar Kharche
  • 2,577
  • 2
  • 24
  • 34
  • `{ $push: { 'settings.clientSetting': { type: req.body.value } } }` Since `settings` is not an "array" and you don't need a "positional match". – Neil Lunn May 07 '18 at 12:25
  • I tried with this { $push: { 'settings.clientSetting': { type: req.body.value } but didn't working!! @NeilLunn – Sagar Kharche May 07 '18 at 12:26
  • Nope that's the correct one. Please don't ever say "I tried this" to anything that is not actually stated in your question. Go and "really do it" rather than comment "i tried" 2 seconds after someone told you better. – Neil Lunn May 07 '18 at 12:28
  • `{ $push: { 'settings.clientSetting': req.body.value } }` of course being the correction. `type` is the mongoose schema type and not an actual property. The mismatch would cause this to be rejected – Neil Lunn May 07 '18 at 12:33

0 Answers0