gpt4 book ai didi

javascript - 在 NodeJS 中动态构建 MongoDB 查询

转载 作者:IT老高 更新时间:2023-10-28 13:35:34 26 4
gpt4 key购买 nike

我收到一个 POST 参数,如下所示:

sort:
[
{ field: 'name', dir: 'asc', compare: '' },
{ field: 'org', dir: 'asc', compare: '' }
]
}

我需要基于它创建一个 MongoDB 查询,所以它应该如下所示:

db.collection("my_collection").find( ... ).sort({'name': 'asc', 'org': 'asc'}).toArray(...);

无论如何,请记住,可以传递更多字段。此外,可能没有传递这些字段,这意味着查询将没有 .sort().

我的问题:如何使用 Node 的 MongoDB 驱动程序动态创建查询?是否有查询生成器或类似的东西?

最佳答案

我发现大多数情况下传递的数据都是独一无二的,因此构建查询对象因项目而异。
所以第一个想法是为 express 创建中间件(在我的例子中),它将查询参数解析为对查询有效的对象。

mongo-native 可以用作 cursor 的链接选项,也可以在对象中使用:

链式:

items.find({ type: 'location' }).sort({ title: 1 }).limit(42).toArray(function(err, data) {
// ...
});

非链式:

items.find({ type: 'location' }, { sort: { title: 1 }, limit: 42 }).toArray(function(err, data) {
// ...
});

正如你所看到的,非链式可以接受一切作为对象,而链式在每个方法之后返回光标并且可以重用。所以通常你有两种选择:

对于链式:

var cursor = items.find({ type: 'location' });
if (sort) {
cursor.sort(sort);
}
cursor.toArray(function(err, data) {
// ...
});

对于非链式:

var options = { };
if (sort) {
options.sort = sort;
}
items.find({ type: 'location' }, options).toArray(function(err, data) {
// ...
});

请务必记住,查询中的任何数据都必须经过正确验证和解析。同样,如果您正在开发 API(例如),并且将决定更改传递排序参数的方式或想要添加新的方式,那么制作中间件(在 express.js 中)来解析这些数据 - 是要走的路.

分页示例:

function pagination(options) {
return function(req, res, next) {
var limit = options.limit ? options.limit : 0;
var skip = 0;

if (req.query.limit) {
var tmp = parseInt(req.query.limit);
if (tmp != NaN) {
limit = tmp;
}
}
if (req.query.skip) {
var tmp = parseInt(req.query.skip);
if (tmp != NaN && tmp > 0) {
skip = tmp;
}
}

if (options.max) {
limit = Math.min(limit, options.max);
}
if (options.min) {
limit = Math.max(limit, options.min);
}

req.pagination = {
limit: limit,
skip: skip
};
next();
}
}

用法:

app.get('/items', pagination({
limit: 8, // by default will return up to 8 items
min: 1, // minimum 1
max: 64 // maximum 64
}), function(req, res, next) {
var options = {
limit: req.pagination.limit,
skip: req.pagination.limit
};
items.find({ }, options).toArray(function(err, data) {
if (!err) {
res.json(data);
} else {
next(err);
}
});
});

和网址示例:

http://example.com/items  
http://example.com/items?skip=64
http://example.com/items?skip=256&limit=32

因此,这是开发灵活的框架的方法,它不会创建任何关于如何编码以及解决您的挑战的规则。

关于javascript - 在 NodeJS 中动态构建 MongoDB 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721347/

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