gpt4 book ai didi

arangodb - 使用 arangojs 将参数传递给 db.query

转载 作者:行者123 更新时间:2023-12-03 06:44:02 25 4
gpt4 key购买 nike

我在使用 ArangoJS 库发送参数时遇到问题,想知道是否有人可以提供帮助。

在下面的示例中,如果参数值在查询中,则可以执行 db.query,但是一旦我尝试使用bindVars,我就会收到静默错误,并且无法提取任何错误详细信息。

var db = require('arangojs')("http://127.0.0.1:8529");

/*
The '_system' database contains a collection called 'test' that contains one document:
{
"a": 1,
"b": 2
}
*/

// This works
db.query('FOR t IN test FILTER t.a == 1 RETURN t')
.then((cursor) => {
cursor.all()
.then(vals => {
console.log("\nNo bindVars");
console.log(vals);
});
});

// This does not work
db.query("FOR t IN @first FILTER t.a == @second RETURN t", { first: "test", second: 1 })
.then((cursor) => {
cursor.all()
.then(vals => {
console.log("\nUsing bindVars");
console.log(vals);
});
});

我是 Node.js 和 ArangoDB 的新手,希望能够使用正确的参数化查询。

我还假设这种参数的使用可以保护您免受 SQL 注入(inject)式攻击?

谢谢!

最佳答案

问题不在于 JavaScript 驱动程序或 Node,问题在于查询本身:

FOR t IN @first FILTER t.a == @second RETURN t

在 AQL 集合中,不能使用普通绑定(bind)参数注入(inject)名称。这是因为您实际上并没有尝试将参数用作字符串值,而是引用具有该名称的集合。引用the AQL documentation :

A special type of bind parameter exists for injecting collection names. This type of bind parameter has a name prefixed with an additional @ symbol (thus when using the bind parameter in a query, two @ symbols must be used).

换句话说,在 AQL 中,它必须被称为 @@first (而不是 @first),并且在 db.query 的绑定(bind)参数参数中它必须被称为@first(而不仅仅是first)。

当使用 arangojs 时,实际上可以通过使用 aqlQuery template handler 来完全避免这种情况。 :

var aqlQuery = require('arangojs').aqlQuery;
var first = db.collection('test');
var second = 1;

db.query(aqlQuery`
FOR t IN ${first}
FILTER t.a == ${second}
RETURN t
`).then(
cursor => cursor.all()
).then(vals => {
console.log('Using aqlQuery');
console.log(vals);
});

这样,您在编写查询时就不必考虑绑定(bind)参数语法,并且可以编写更复杂的查询,而不必弄乱极长的字符串。请注意,它将识别 arangojs 集合实例并相应地处理它们。使用字符串而不是集合实例会导致与示例中相同的问题。

另外请注意,模板处理程序也存在于 arangosh shell 和 ArangoDB 本身中(例如,当使用 Foxx 时)。

关于arangodb - 使用 arangojs 将参数传递给 db.query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34650706/

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