javascript - 添加到数组 - 没有重复字段值的子文档
问题描述
我正在尝试将对象添加到 MongoDB 中的数组中。我不希望它被复制。
我正在尝试使用$addToset
in更新用户读取数组findOneAndUpdate
。但是,由于时间戳,它正在插入重复;时间戳是一个重要的属性。我不能否定它。我可以根据键插入userId
吗?请告诉我。
{
_id: 'ddeecd8b-79b5-437d-9026-d0663b53ad8d',
message: 'hello world notification',
deliverToUsersList: [ '123-xxx-xx', '124-xxx-xx']
userRead: [
{
isOpened: true,
userId: '123-xxx-xx'
updatedOn: new Date(Date.now()).toISOString()
},
{
isOpened: true,
userId: '124-xxx-xx'
updatedOn: new Date(Date.now()).toISOString()
}
]
}
解决方案
要将没有重复信息的新对象添加到userRead
数组中,您必须在更新方法的查询过滤器中检查重复信息。例如,以下代码将不允许添加具有重复userId
字段值的新对象。
new_userId = "999-xxx-xx"
new_doc = { userId: new_userId, isOpened: true, updatedOn: ISODate() }
db.test_coll.findOneAndUpdate(
{ _id: 'ddeecd8b-79b5-437d-9026-d0663b53ad8d', "userRead.userId": { $ne: new_userId } },
{ $push: { "userRead" : new_doc } },
)
推荐阅读
- php - Ajax 不断从 PHP 返回不正确的输出
- javascript - 如何使用 xlsx npm 库将嵌套的 json 对象转换为 excel 表?
- ios - 当两次选择 tableview 单元格时,它会因发现意外 nil 的错误而崩溃
- ios - 无法通过情节提要为活动指示器设置动画
- mysql - 使用 .NET Core 服务从 MySQL 读取 č、ć 和 đ
- javascript - 如何从地理编码器中仅获取城市名称?
- r - ggplot2 在 geom_bar 边界中的间隙
- excel - Excel VBA /根据字符数将字符串拆分为列
- c++ - 具有不同返回类型的变体访客
- java - 如何用 IP 和端口划分字符串?