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

oxf4rvwz  于 2022-12-09  发布在  Go
关注(0)|答案(4)|浏览(168)

假设我有一个已经存在于数据库中的Col1集合。

var col = db.collection('Col1');
col.save({"name":"something"});

会非常好地工作。
但是如果一个Col2集合在我的数据库中还不存在,那么就用同样的方法来尝试,也就是

var col = db.collection('Col2');
col.save({"name":"something"})

我也能很好地工作。只是它不存在,不会显示在我的数据库中。如果它抛出了一些错误或东西,我可以使用trycatch语句来得到结果。但既然这是现成的,我怎么知道一个集合是否已经存在呢?

bttbmeg0

bttbmeg01#

这里有两件事可能会让人困惑。
首先,arangojs(与ArangoDB的内部JS API不同)对于需要与实际ArangoDB服务器通信的所有内容都是 * 异步的 *。
您可以传递node.js-style回调(就像内置node.js模块中的异步函数,例如fshttp或者,您可以省略回调,方法将返回对结果的承诺。您可以了解更多关于承诺如何工作的信息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);
});

或者使用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);
}

或者使用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
    });
  });
});
yqhsw0fo

yqhsw0fo2#

col.save不会立即执行保存操作,而是返回一个promise。因此,它始终会成功。解决方法是等待promise得到解决,然后根据是否发生错误做出React:

var col = db.collection('Col2');
col.save({"name":"something"}).then(
  meta => console.log('Document saved:', meta._rev),  
  err => { console.error('Failed to save document:', err.errorNum, err.response.body.errorMessage); }
);
pkln4tw6

pkln4tw63#

https://docs.arangodb.com/3.1/Manual/DataModeling/Collections/DatabaseMethods.html#collection 国家
返回单个集合或空db._collection(集合名称)
因此您可以使用

var col2 = db._collection('Col2');
if (col2) {
    // collection exists
    col2.save({"name":"something"});
}
9avjhtql

9avjhtql4#

这是旧的,但有一个exists()函数。
typescript/node中的示例

const metaResult = db.collection('myCollection');
if(!await metaResult.exists()) {
    await db.createCollection('myCollection');
}

相关问题