gpt4 book ai didi

javascript - 在nodejs中将现有对象查找到数组中

转载 作者:行者123 更新时间:2023-11-30 15:25:00 25 4
gpt4 key购买 nike

您好,这是我的收藏,如果两个 userId 都存在于订阅者数组中,我只想将 userId 查看到订阅者数组中,而不是创建新集合返回相同的 channelId。如果两个 userId 都不存在于 subcriber 数组中,那么创建新文档我如何在数组中搜索 userids。这是我的收藏。

{
"_id" : ObjectId("58dd1013e973fc0004743443"),
"createdAt" : ISODate("2017-03-30T14:02:59.175Z"),
"updatedAt" : ISODate("2017-03-30T14:02:59.175Z"),
"timestamp" : "2017-03-30",
"channelId" : "CH-EU7D",
"createdById" : "58dcc3cd9a7a301308b62857",
"message" : "",
"subcriber" : [
{
"userId" : "58dcc3cd9a7a301308b62857",
"channelId" : "CH-EU7D",
"_id" : ObjectId("58dd1013e973fc0004743444"),
"status" : "accepted"
},
{
"userId" : "58dcc3ec9a7a301308b62859",
"channelId" : "CH-EU7D",
"_id" : ObjectId("58dd1013e973fc0004743445"),
"status" : "pending"
}
],
"__v" : 0

我已经试过了,但没有用。

Channel.find({ 'subcriber.userId': b.userId }, { $and: [{ 'subcriber.userId': b.friendId }] }

最佳答案

在 nodejs 中你可以使用 JavaScript Array.prototype.some()方法与您的 json 数组来测试是否有任何匹配的 useId,您需要编写如下内容:

function checkUserId(array, userId) {
return array.some(function(element) {
return userId === element.userId;
});
}

这是一个演示片段:

function checkUserId(array, userId) {
return array.some(function(element) {
return userId === element.userId;
});
}


var json = {
"_id": "58dd1013e973fc0004743443",
"createdAt": "2017-03-30T14:02:59.175Z",
"updatedAt": "2017-03-30T14:02:59.175Z",
"timestamp": "2017-03-30",
"channelId": "CH-EU7D",
"createdById": "58dcc3cd9a7a301308b62857",
"message": "",
"subcriber": [{
"userId": "58dcc3cd9a7a301308b62857",
"channelId": "CH-EU7D",
"_id": "58dd1013e973fc0004743444",
"status": "accepted"
},
{
"userId": "58dcc3ec9a7a301308b62859",
"channelId": "CH-EU7D",
"_id": "58dd1013e973fc0004743445",
"status": "pending"
}
]
};

//Check an existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a301308b62859"));

//Check a non existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a3000000000859"));

关于javascript - 在nodejs中将现有对象查找到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43135305/

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