gpt4 book ai didi

javascript - Mongodb mongoose - 如果字段不存在,如何将文档添加到数组

转载 作者:行者123 更新时间:2023-11-29 10:26:14 25 4
gpt4 key购买 nike

这样的文档

{
"_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 应该在数组中保持唯一。

我该怎么做?

最佳答案

deviceId 为传入对象已经存在。 $push

Mongo 查询:

const incomingDoc = {
deviceId: "1233",
userAgent: "PostmanRuntime/7.19.0",
online: false,
_id: ObjectId("5db65eb2a2f3a61fe88e162b"),
loginAt: ISODate("2019-10-28T03:21:22.178+0000")
};

db.collection.update(
{
_id: idToFilterIfAny,
"devicesCxt.deviceId": { $ne: incomingDoc.deviceId }
},
{ $push: { devicesCxt: incomingDoc } }
);

关于javascript - Mongodb mongoose - 如果字段不存在,如何将文档添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58591608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com