gpt4 book ai didi

node.js - Mongoose 没有带来任何结果

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:43 26 4
gpt4 key购买 nike

我正在尝试在 Mongoose 中构建一种复杂的查询,我的问题是该查询可以接收的所有参数都是非强制性的,这给我带来了问题。现在我这样做了:

let query = {
publicationType: req.body.searchParams.publicationType
};
if (req.body.searchParams.address) {
query.address = {};
if (req.body.searchParams.address.city) {
query.address.city = req.body.searchParams.address.city;
}
}
try {
const dwellings = await model.Dwelling.find({
$and: [{$or: [{publicationType: req.body.searchParams.publicationType}]},
{
$or: [{
address: [query.address]
}]
}]
}).lean().exec();
console.log(dwellings);
res.send({dwellings});
} catch (err) {
next(err);
}
});

这是为了尝试城市参数是否有效,如果我仅按发布类型搜索,我会得到所需的结果,如果我添加城市,即使我应该获得更多结果,我也会得到 0 个结果,我调试了 mongoose 以查看查询是如何构建的,如下所示:

Mongoose: dwelling.find({ '$and': [ { '$or': [ { publicationType: 'Venta' } ] }, { '$or': [ { address: { '$in': [ { city: 'La Plata' } ] } } ] } ] }, { fields: {} })
[]

最佳答案

在您的代码中,您正在构建一个 $and expression两个 $or expressions 但是每个 $or 表达式只有一个参数,因此您可以有效地构建此 $and find 表达式 (请注意,我使用下面的 mongo shell 语法):

db.dwellings.find({ 
'$and': [
{ publicationType: 'Venta' },
{ address: { '$in': [ { city: 'La Plata' } ] } }
]
});

...换句话说:“查找带有publicationType Venta address.city La Plata的住宅.

if I add city I get 0 results even when I'm supposed to get more

既然您提到您希望在添加 address.city 时获得更多结果,我怀疑您确实希望顶级表达式为 $or 而不是 $和,像这样:

db.dwellings.find({ 
'$or': [
{ publicationType: 'Venta' },
{ address: { '$in': [ { city: 'La Plata' } ] } }
]
});

在将查询表达为代码之前,您可能希望在 mongo shell 中对查询进行更多试验。如果您的工作站上恰好有 Docker,我发现在容器中运行 mongo 是一种在开发时进行原型(prototype)设计的有用方法,例如:

docker run --name mongo -d mongo:3.7
# after mongo is up and running...
docker exec -it mongo mongo

在交互式 mongo shell 中,您可以插入文档进行测试并使用 find 表达式进行实验,例如:

use stackoverflow;
dwell1 = { publicationType: 'Venta', address: { city: 'Somewhere' } };
dwell2 = { publicationType: 'Something', address: { city: 'La Plata' } };
db.dwellings.insert(dwell1);
db.dwellings.insert(dwell2);

# Try results of $and
db.dwellings.find({ '$and': [
{ publicationType: 'Venta' },
{ address: { '$in': [ { city: 'La Plata' } ] } }
] });

# ... compare to results of $or
db.dwellings.find({ '$or': [
{ publicationType: 'Venta' },
{ address: { '$in': [ { city: 'La Plata' } ] } }
] });

...插入一些文档进行测试后,确认您是否需要在 find 中使用 $and$or 表达式.

关于node.js - Mongoose 没有带来任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50452056/

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