Search code examples
node.jsmongodbmongoose

How to push to mongoose objects?


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


Solution

  • 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