Home > Blockchain >  Push new Object inside a document array
Push new Object inside a document array

Time:06-16

I have this schema for my user

const userSchema = mongoose.Schema({
   
   firstName: {
        type: String,
      
    },

   notifications : [{
    description: String,
    status: {
        type: String,
        enum : ['read', 'unread'],
        default: 'unread'
    },
    dateAdded:{
        type: Date,
        default: Date.now
    }
    }],
})

supposedly I want to find the user _id first then insert a new object inside the new notification array. and it should look like this

{ 
  _id: ObjectId('123')
  firstName: 'John Doe'
  notifications:[
   {
     description: 'somedescription'
     status: 'unread'
 
   },
   {
     description: 'somedescription2'
     status: 'unread'
   }
   
  ]

}

How can I achieve this, assuming that the notification property is non existent in the user document first, i need to check if notification property is present else add the notification property and push the new object


  User.updateOne(
     { _id: userId },
     { $push: { notifications: {description: 'new notifications'}  } }
  )

this code is not working for me

CodePudding user response:

Use $addToSet operator to achieve that

  User.updateOne(
     { _id: userId },
     { $addToSet: { notifications: {description: 'new notifications'}  } }
  )

If that doesn't work try to add the default value too, and then that must work

  User.updateOne(
         { _id: userId },
         { $addToSet: { notifications: {description: 'new notifications',
  'status': 'unread'}  } }
 )
  • Related