我有我的用戶的這個架構
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'} } }
)
這段代碼對我不起作用
uj5u.com熱心網友回復:
使用 $addToSet 運算子來實作
User.updateOne(
{ _id: userId },
{ $addToSet: { notifications: {description: 'new notifications'} } }
)
如果這不起作用,請嘗試添加默認值,然后它必須起作用
User.updateOne(
{ _id: userId },
{ $addToSet: { notifications: {description: 'new notifications',
'status': 'unread'} } }
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/491753.html
標籤:javascript 数组 mongodb 猫鼬
