簡體   English   中英

在文檔數組中推送新對象

[英]Push new Object inside a document array

我有我的用戶的這個架構

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

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

據說我想先找到用戶_id,然后在新的通知數組中插入一個新對象。 它應該看起來像這樣

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

}

我該如何實現這一點,假設通知屬性首先在用戶文檔中不存在,我需要檢查通知屬性是否存在,否則添加通知屬性並推送新對象


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

這段代碼對我不起作用

使用 $addToSet 運算符來實現

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

如果這不起作用,請嘗試添加默認值,然后它必須起作用

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM