使用arangojs和aqlQuery在ArangoDb中将集合名称用作变量时出错

Dav*_*mas 3 node.js arangodb arangojs

我已经做了几个月的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)
});
Run Code Online (Sandbox Code Playgroud)

我在干净的npm安装上测试了这个,只有arangojs 4.3.0和Node 4.4.0或Node 5.5.0(使用nodist).

有没有其他人在模板字符串中看到集合名称的问题?

Ala*_*lum 8

arangojs文档没有明确指出这一点,AQL文档掩盖了这一点,但集合绑定变量是专门处理的.当手动编写AQL查询时,这意味着您需要在其名称前加上一个@,bindVars并相应地使用@@前缀而不是通常引用它们@.

因为没有办法识别字符串是指字符串值还是集合名称,所以在aqlQuery中使用集合作为绑定变量正确方法是传入arangojs集合对象而不是字符串本身,例如:

const collection = db.collection(collectionName);
db.query(aqlQuery`
  INSERT { "something": ${sampleText} }
  IN ${collection}
  RETURN NEW._key
`)
Run Code Online (Sandbox Code Playgroud)

如果将aqlQuery模板的输出记录到控制台,您将看到查询正确插入带@@前缀的引用,绑定变量包含@前缀变量,其值为集合的名称(而不是您传入的集合对象) ).