【发布时间】:2020-02-23 18:13:29
【问题描述】:
这样的文件
{
"_id" : ObjectId("5db65eb2a2f3a61fe88e162a"),
"devicesCxt" : [
{
"deviceId" : "1232",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162c"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
}
],
}
我想添加这个
{
"deviceId" : "1233",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162b"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
}
我想要这样的东西
{
"_id" : ObjectId("5db65eb2a2f3a61fe88e162a"),
"devicesCxt" : [
{
"deviceId" : "1232",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162c"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
},
{
"deviceId" : "1233",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162b"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
}
],
}
如果deviceId: 1232不允许,否则deviceId: 1233可以成功。
deviceId 不能有相同的对象
deviceId 在数组中应保持唯一。
我该怎么做?
【问题讨论】:
-
谢谢 Jayakumar Thangavel,这不是我想要的,我希望 deviceId 不要重复
-
您可以尝试在 deviceId 字段上创建
unique index。 -
我正在尝试寻找一种方法来确定添加时是否存在 deviceId
-
@Amorous 如果我理解正确,如果它不包含具有相同
deviceId.. 的对象,您想更新/添加新传入对象到devicesCxt数组。对吗?
标签: javascript node.js mongodb mongoose