我已经使用 arangojs 几个月了,最近我的一些代码开始失败,而这些代码曾经可以正常工作,关于在使用模板字符串和 aqlQuery 时将变量用作集合名称。
我在 Windows 10 上使用 Node.js 4.4.0。
此示例代码显示错误:
// Issue with template string and arangodb with collection names
var arango = require('arangojs');
var aqlQuery = require('arangojs').aqlQuery;
var db = new arango('http://127.0.0.1:8529');
var collectionName = 'sampleCollection';
// Connect to _system
db.useDatabase('_system');
var sampleText = "Testing Only";
/* Add a record to the collection, using template string with collectionName
* If I use ${collectionName} I get the error code 400:
* error: 'bind parameter \'bind parameter \'value1\' has an invalid value or type near
* \'RETURN NEW._key\n
* \' at position 4:9\' has an invalid value or type (while parsing)',
*
* If I write out the collection name, or use a normal db.query style query without using
* aqlQuery and template strings and pass the table name as @collectionName, then it works
* fine.
*/
db.query(aqlQuery`
INSERT { "something": ${sampleText} }
IN ${collectionName}
RETURN NEW._key
`).then(cursor =>
cursor.all()
).then(vals => {
console.log(`Created a new document with a _key of ${vals[0]}`)
}).catch(err => {
console.log(err)
});
我已经在仅使用 arangojs 4.3.0 和 Node 4.4.0 或 Node 5.5.0(使用 nodist)的干净 npm 安装上对此进行了测试。
有没有其他人看到模板字符串中集合名称的问题?
最佳答案
aragojs 文档没有明确指出这一点,AQL 文档也掩盖了这一点,但对集合绑定(bind)变量进行了特殊处理。手动编写 AQL 查询时,这意味着您需要在 bindVars
中为它们的名称添加前缀 @
并相应地使用 @@
前缀引用它们而不是通常的 @
。
因为无法识别字符串是指字符串值还是集合名称,correct way to use collections as bind variables in aqlQuery是传入一个arangojs集合对象而不是字符串本身,例如:
const collection = db.collection(collectionName);
db.query(aqlQuery`
INSERT { "something": ${sampleText} }
IN ${collection}
RETURN NEW._key
`)
如果将 aqlQuery 模板的输出记录到控制台,您将看到查询正确地插入了带有 @@
前缀的引用,并且绑定(bind)变量包含 @
前缀变量,其值是集合的名称(而不是您传入的集合对象)。
关于node.js - 使用 arangojs 和 aqlQuery 在 ArangoDb 中使用集合名称作为变量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36761420/