gpt4 book ai didi

node.js - 多字段传递获取查询失败

转载 作者:行者123 更新时间:2023-12-05 04:20:11 25 4
gpt4 key购买 nike

我正在尝试根据不同的查询查找用户列表。就像我传递 firstnamelastnamelocation 我想要基于其中一个或所有数据的数据,但我没有得到细节。还有 2 个嵌套字段我想通过检查。这些在此处 "otherDetails.nationality": "Indian""professionalDetails.type": "Cook"。每当我向它们传递一个查询检查时,我都会得到所需的数据,但是每当我将它们全部放入 $or 聚合方法中时,它就会失败并为我提供数据库中的所有数据。在这里卡了2天没解决。帮助将不胜感激

这里是数据库数据的一瞥。不要使用相同的一条记录,我复制了多次,我还删除了一些我让它干净的字段

[{
"_id": "604670a613a06f0017702d88",
"firstname": "Babulal ",
"lastname": "Gadri",
"mobile": "00000000000",
"otherDetails": {
"nationality": "Indian"
},
"professionalDetails": {
"type": "Cook"
}
}

{
"_id": "604670a613a06f0017702d8a",
"firstname": "Babulal ",
"lastname": "Gadri",
"mobile": "00000000000",
"otherDetails": {
"nationality": "Indian"
},
"professionalDetails": {
"type": "Cook"
}
}
{
"_id": "604670a613a06f0017702d8b",
"firstname": "Babulal ",
"lastname": "Gadri",
"mobile": "00000000000",
"otherDetails": {
"nationality": "Indian"
},
"professionalDetails": {
"type": "Cook"
}
}
{
"_id": "604670a613a06f0017702d88",
"firstname": "Babulal ",
"lastname": "Gadri",
"mobile": "00000000000",
"otherDetails": {
"nationality": "Indian"
},
"professionalDetails": {
"type": "Cook"
}
}
{
"_id": "604670a613a06f0017702d8c",
"firstname": "Babulal ",
"lastname": "Gadri",
"mobile": "00000000000",
"otherDetails": {
"nationality": "Indian"
},
"professionalDetails": {
"type": "Chef"
}
}

]

这是我正在做的功能

searchCookForNotification: async function (req, res) {
let { type, nationality, firstname, lastname, location } = req.query;

var db = Person.getDatastore().manager;

var cooks = await db
.collection(Person.tableName)
.find({
$or: [
{ firstname },
{ lastname },
{ location },
{ "professionalDetails.type": type },
{ "otherDetails.nationality": nationality },
],
})
.toArray();

console.log("Length: ", cooks.length);

return res.successResponse(
cooks,
200,
null,
true,
"Cooks found successfully"
);
},
};

最佳答案

这只是因为代码本身不稳定,如果其中一个参数不存在于“查询”中,例如缺少“位置”,那么您在 $or 查询中创建的条件将执行以下查询:

{ location: undefined }

您提供的示例与所有文档匹配。我想您只是想根据给定的输入动态构建查询:

let { type, nationality, firstname, lastname, location } = req.query;
var db = Person.getDatastore().manager;

const orCondArray = [];
if (firstname) {
orCondArray.push({ firstname })
}
if (lastname) {
orCondArray.push({ lastname })
}
if (location) {
orCondArray.push({ location })
}
if (type) {
orCondArray.push({ "professionalDetails.type": type })
}
if (nationality) {
orCondArray.push({ "otherDetails.nationality": nationality })
}

if (orCondArray.length) {
var cooks = await db
.collection(Person.tableName)
.find({$or: orCondArray})
.toArray();
}

关于node.js - 多字段传递获取查询失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74582747/

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