如何检查 ArangoDB 中是否已存在集合

Pra*_*nna 5 node.js arangodb arangojs

假设Col1我的数据库中已经存在一个集合。所以,做类似的事情:

var col = db.collection('Col1');
col.save({"name":"something"});
Run Code Online (Sandbox Code Playgroud)

会工作得很好。

Col2但是,如果我的数据库中尚不存在的集合尝试使用相同的东西,即

var col = db.collection('Col2');
col.save({"name":"something"})
Run Code Online (Sandbox Code Playgroud)

也会工作得很好。只是它不存在并且不会显示在我的数据库中。如果它抛出一些错误或我可以使用的内容trycatch结果语句。但既然这是不可能的,我怎么知道集合是否已经存在?

Ala*_*lum 3

这里发生的两件事可能会令人困惑。

首先,arangojs(与 ArangoDB 的内部 JS API 不同)对于需要与实际 ArangoDB 服务器通信的所有内容都是异步的。异步函数在文档中被标记为“async”。

您可以将 Node.js 风格的回调(如内置 Node.js 模块中的异步函数,例如 、 等)传递fshttp这些方法。或者,您可以简单地省略回调,该方法将返回结果的承诺。您可以在 Mozilla 的 JavaScript 参考文档中了解有关 Promise 如何工作的更多信息(这不是 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);
});
Run Code Online (Sandbox Code Playgroud)

或者使用 async/await (如果你使用 Babel 或一年后阅读这个答案):

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);
}
Run Code Online (Sandbox Code Playgroud)

或者使用 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
    });
  });
});
Run Code Online (Sandbox Code Playgroud)