[英]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.