有两件事情怎么回事,可能会造成混乱。首先,arangojs(不像ArangoDB的内部JS API)是异步,用于需要与实际的ArangoDB服务器交谈的所有内容。文档中的异步函数被标记为“异步”。
您可以将node.js样式的回调(如内置node.js模块中的异步函数,例如fs
,http
等)传递给这些方法。或者,您可以简单地省略回调,该方法将返回结果的承诺。您可以详细了解承诺如何工作in Mozilla's JavaScript reference documentation(这不是特定于Mozilla--它们的引用非常好,通常是正确的)。
您遇到的另一件事是arangojs中的集合对象与ArangoDB中的实际集合之间的区别。驱动程序允许您为集合创建集合对象,而不管它们是否存在。当试图使用它们,如果集合实际上不存在,你当然会看到一个错误。
var col = db.collection('whatever');
col.create() // create the collection if it doesn't exist
.catch(function() {}) // ignore any errors
.then(function() {
return col.get(); // make sure the collection exists now
})
.then(function() {
return col.save({some: 'data'});
})
.then(function (result) {
// everything went fine
})
.catch(function (e) {
console.error('Something went wrong', e.stack);
});
或者使用异步/等待(如果你用巴贝尔或者从现在看这个答案一年):
var col = db.collection('whatever');
try {
await col.create(); // create the collection if it doesn't exist
} catch (e) {} // ignore any errors
try {
await col.get(); // make sure the collection exists now
const result = await col.save({some: 'data'});
// everything went fine
} catch (e) {
console.error('Something went wrong', e.stack);
}
或者如何使用Node.js风格的回调,因为你是老校友或很喜欢金字塔:
var col = db.collection('whatever');
col.create(function() { // create the collection if it doesn't exist
// ignore any errors
col.get(function (err) { // make sure the collection exists now
if (err) {
console.error('Something went wrong', err.stack);
return;
}
col.save({some: 'data'}, function (err, result) {
if (err) {
console.error('Something went wrong', err.stack);
return;
}
// everything went fine
});
});
});
尽管arangoDB的文档说它可以工作,但节点的软件包'arangojs'不同意它。对于不存在的集合,我的代码保存在if子句中时显示为“true”。 我想要一个arangojs解决方案。目前,我只是在所有收藏列表中检查收藏名称以检查收藏的存在。但是我的方法很粗糙,我自己也不喜欢 – Prasanna