Passing parameters to db.query with arangojs

廉价感情. 提交于 2019-12-04 05:03:19

The problem isn't with the JavaScript driver or Node, the problem is with the query itself:

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

In AQL collection names can't be injected with ordinary bind parameters. This is because you're not actually trying to use the parameter as a string value but to refer to a collection with that name. To quote 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).

In other words, in AQL it has to be called @@first (instead of @first) and in the bind parameters argument to db.query it has to be called @first (instead of just first).

When using arangojs it's actually possible to avoid this entirely by using the 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);
});

This way you don't have to think about bind parameter syntax when writing queries and can write more complex queries without having to mess with extremely long strings. Note that it will recognize arangojs collection instances and handle them accordingly. Using a string instead of a collection instance would result in the same problems as in your example.

Additionally note that the template handler also exists in the arangosh shell and in ArangoDB itself (e.g. when using Foxx).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!