0

cannot add additional objects into object list.

i have a schema that follows

apps: {
    type: Array,
    required: true,
    default: [],
  },
  username: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  registeredDate: {
    type: Date,
    required: true,
    default: Date.now,
  }

i am able to add to apps object by doing something like

user = await User.findOne({ username: req.body.username });
user.apps[req.body.id] = {
   isUser: false,
   order: null,
};

await user.save()

This work for the first object.

But if i want to add another object instance inside apps again, i try the same code which works on NodeJS, i am able to see it in console.log(), but when i login to my database, i can only see the first object that was added. How would i be able to push any additional objects?

Thank you

  • What is, and why do you use `req.body.id` to index `user.apps`? – rickhg12hs Mar 11 '23 at 03:18
  • `user.apps[req.body.id]` is [setting a property](https://stackoverflow.com/a/9526896/1409374) of `user.apps`, not increasing the _"data storage"_ of the array. – rickhg12hs Mar 11 '23 at 03:33

1 Answers1

1

add another object instance inside apps

you need use query update|| updateOne to add new object with operator $push

await user.updateOne(
  { username: req.body.username },
  {
    $push: { apps: {
        key1Example: 'valueExample1',
        key2Example: 'valueExample2',
    } },
  }
);

try it in MONGO-PLAYGROUND

Tobok Sitanggang
  • 607
  • 5
  • 15