您好我正在使用mongoDB,我正在尝试创建一个动态对象并将其作为参数传递给find()
我的对象是这样的
库
var search = {};
if(data.orderId) {
search["_id"] = { $in: data.orderId.split(",") } ;
}if(data.path) {
search["stops.districtId"] = data.path;
}if(data.special) {
search["special.option"] = { $in: data.special.split(",") } ;
}if(data.userInfo) {
search["UserId"] = data.userInfo;
}
然后我会将我的搜索对象传递给像这样的查询
模型
var col = db.collection( CustomerOrderModel.collection() );
col.find(
{
serviceType:data.serviceType,
**search**
}
).skip(data.skip).limit(data.limit).sort(data.sort).toArray(function(err, res) {
if (err) {
reject( err );
} else {
resolve( res );
}
});
这里的问题是当我在console.log中搜索我的搜索对象时
'special.option': { '$in': [ 'ROUND_TRIP' ] } }
我的$ in用引号括起来。所以我的查询不起作用。
如果我在查询中直接输入"special.option": { $in: [ 'ROUND_TRIP' ] } }
,它就能正常工作。
我正在尝试构建此搜索对象,因为我有多个字段可以使用复杂逻辑进行搜索。我不想在我的身上做这些 模型,所以我将在我的库中创建搜索对象。
是否有任何可能的方法,提前谢谢。
答案 0 :(得分:1)
这不是问题。
console.log({ "special.option": { $in: [ 'ROUND_TRIP' ] } });
给出
{ 'special.option': { '$in': [ 'ROUND_TRIP' ] } }
所以这是正确的。
在您的代码中,您只需在最关键的部分编写**search**
,但请尝试以下操作:
search["serviceType"] = data.serviceType;
col.find( search )
答案 1 :(得分:1)
您应该通过在搜索对象中添加额外的过滤器来使搜索对象成为查询的一部分。正如您目前所做的那样
col.find({
serviceType:data.serviceType,
search
})
这被视为
col.find({
serviceType:data.serviceType,
{ 'special.option': { '$in': [ 'ROUND_TRIP' ] } }
})
您应该可以使用方括号表示法将serviceType
过滤器添加到现有搜索对象中,如下所示:
search["serviceType"] = data.serviceType;
然后您可以在查询中传递该对象:
var col = db.collection( CustomerOrderModel.collection() );
search["serviceType"] = data.serviceType;
col.find(search)
.skip(data.skip)
.limit(data.limit)
.sort(data.sort)
.toArray(function(err, res) {
if (err) { reject( err ); }
else { resolve( res ); }
});