MongoDB和Node.js中的动态查询 [英] Dynamic queries in MongoDB and Node.js
问题描述
我正在后台使用Mongodb的nodejs / express应用程序。在我的一个API调用中,根据特定的querystring参数的存在,或者另一个我想使用$ gt或$ lt。
向Mongodb发出查询。 p>在某些情况下,我们想要使用$ lt,而不是
tokenId
要求的东西,但在其他情况下,我们希望所有大于 tokenId
使用$ gt。 以下是一个示例查询:
<$ ({'_ id':-1})。 toArray(function(error,films)
有没有办法动态创建查询而不实际做2不同的查询?
以编程方式构建查询对象:
var query = {'film_id':{$ in:genre}};
if(param){
query._id = {$ lt:tokenId};
} else {
query._id = {$ gt; tokenId};
}
collection.find(query).sort({'_ id':-1})。 (25).toArray(function(error,films);
更新
现在Node.js 4+支持计算的属性名称,您可以一步创建查询
:
var query = {
film_id:{$ in:genre},
_id:{[param? '$ lt':'$ gt']:tokenId}
};
I am working on a nodejs/express app with Mongodb on the backend. In one of my API calls, depending on the presence of a particular querystring parameter or the other I want to issue a query to Mongodb with either a $gt or a $lt.
In some cases we want to ask for everything less than the tokenId
using $lt, but in other cases we want everything greater than the tokenId
using $gt. How do we do that without duplicating the queries?
Here's an example query:
collection.find({'film_id': {$in : genre}, '_id': {$lt: tokenId}}).sort({'_id': -1}).limit(25).toArray(function(error, films)
Is there a way to dynamically create the query without actually doing 2 different queries?
Build up your query object programmatically:
var query = {'film_id': {$in : genre}};
if (param) {
query._id = {$lt: tokenId};
} else {
query._id = {$gt: tokenId};
}
collection.find(query).sort({'_id': -1}).limit(25).toArray(function(error, films);
Update
Now that Node.js 4+ supports computed property names, you can create query
in one step as:
var query = {
film_id: {$in: genre},
_id: {[param ? '$lt' : '$gt']: tokenId}
};
这篇关于MongoDB和Node.js中的动态查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!