MongoDB 和 Node.js 中的动态查询 [英] Dynamic queries in MongoDB and Node.js

查看:19
本文介绍了MongoDB 和 Node.js 中的动态查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个带有 Mongodb 后端的 nodejs/express 应用程序.在我的一个 API 调用中,根据特定查询字符串参数的存在或另一个我想使用 $gt 或 $lt 向 Mongodb 发出查询.

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.

在某些情况下,我们希望使用 $lt 请求小于 tokenId 的所有内容,但在其他情况下,我们希望使用 $gt 请求所有大于 tokenId 的内容.我们如何在不重复查询的情况下做到这一点?

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?

这是一个示例查询:

collection.find({'film_id': {$in : genre}, '_id': {$lt: tokenId}}).sort({'_id': -1}).limit(25).toArray(function(error, films)

有没有一种方法可以在不实际执行 2 个不同查询的情况下动态创建查询?

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);

更新

现在 Node.js 4+ 支持 计算属性名称,你可以一步创建query:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆