如何在 Node.js 中使用 ArangoDB?
首先創建一個文件夾,然後進入這個文件夾,運行 npm init
來創建 NodeJS 項目。
mkdir arangodb_node
cd arangodb_node
npm init
安裝JavaScript 驅動程序
npm install arangojs@5
NodeJS 代碼
方法 | 含義 |
---|---|
🐻數據庫操作 | – |
createDatabase() | 創建數據庫 |
useDatabase() | 切換數據庫 |
🐼集合操作 | – |
create() | 創建集合 |
🐱文檔操作 | – |
save() | 保存(新增)文檔 |
update() | 更新文檔 |
document() | 查看文檔 |
remove() | 刪除文檔 |
基本操作
// require 導入
Database = require('arangojs').Database;
db = new Database('http://127.0.0.1:8529');
// 引包
var Database = require('arangojs').Database
// 連接
const username = 'root' // default user
const password = '' // blank password by default
var db = new Database('http://127.0.0.1:8529');
db.useBasicAuth(username, password);
// console.log(db);
// 創建數據庫
db.createDatabase('mydb').then(
() => console.log('Database created'),
err => console.error('Failed to create database:', err)
);
// 切換數據庫
db.useDatabase('mydb');
// console.log(db);
// 創建集合
var collection = db.collection('firstCollection');
collection.create().then(
() => console.log('Collection created'),
err => console.error('111Failed to create collection:', err)
);
// 創建文檔
var doc = {
_key: 'firstDocument',
a: 'foo',
b: 'bar',
c: Date()
}
// 保存文檔
collection.save(doc).then(
meta => console.log('Document saved:', meta._rev),
err => console.error('Failed to save document:', err)
);
// 更新文檔
collection.update('firstDocument', {
age: 18
}).then(
meta => console.log('Document updated:', meta._rev),
err => console.error('Failed to update document:', err)
);
// 查看文檔
collection.document('firstDocument').then(
doc => console.log('Document:', JSON.stringify(doc, null, 2)),
err => console.error('Failed to fetch document:', err)
);
// 刪除文檔
collection.remove('firstDocument').then(
() => console.log('Document removed'),
err => console.error('Failed to remove document', err)
);
// 驗證刪除
collection.document('firstDocument').then(
doc => console.log('Document:', JSON.stringify(doc, null, 2)),
err => console.error('Failed to fetch document:', err.message));
// 批量導入
docs = [];
for (i = 0; i < 10; i++) {
docs.push({
_key: `doc${i + 1}`,
value: i
});
}
collection.import(docs).then(
result => console.log('Import complete:', result),
err => console.error('Import failed:', err)
);
// 簡單查詢
collection.all().then(
cursor => cursor.map(doc => doc._key)
).then(
keys => console.log('All keys:', keys.join(', ')),
err => console.error('Failed to fetch all documents:', err)
);
// AQL 查詢
db.query('FOR d IN firstCollection SORT d.value ASC RETURN d._key').then(
cursor => cursor.all()
).then(
keys => console.log('All keys:', keys.join(', ')),
err => console.error('Failed to execute query:', err)
);
⚠️ 默認操作的數據庫爲 _system
,如果想在其它數據庫上操作,保持 db.useDatabase('想操作的數據庫名');
常在。
模板操作
當編寫複雜的查詢時,不需要在巨大的字符串中對所有內容進行硬編碼。arangojs 提供了同樣的 aqlQuery
模板處理程序。
// 插入
db.query(aqlQuery `
FOR doc IN ${collection}
LET value = 100 + doc.value
INSERT {
_key: CONCAT("new", doc.value),
value
} INTO ${collection}
RETURN NEW
`).then(
cursor => cursor.map(doc => doc._key)
).then(
keys => console.log('Inserted documents:', keys.join(', ')),
err => console.error('Failed to insert:', err)
);
// 註明:插入數據時doc.value和上面批量導入的數據相關,在上述批量導入的基礎上進行操作。
// 更新
db.query(aqlQuery `
FOR doc IN ${collection}
UPDATE doc WITH {
value: doc.value * 2
} IN ${collection}
RETURN {old: OLD.value, new: NEW.value}
`).then(
cursor => cursor.map(doc => `${doc.old} => ${doc.new}`)
).then(
results => console.log('Update complete:', results.join(', ')),
err => console.error('Update failed:', err)
);
// 刪除
db.query(aqlQuery `
FOR doc IN ${collection}
FILTER doc.value % 10 != 0
REMOVE doc IN ${collection}
RETURN OLD._key
`).then(
cursor => cursor.all()
).then(
keys => console.log('Removed:', keys.join(', ')),
err => console.error('Failed to remove:', err)
);
// 完全清空集合(刪除全部文檔)
collection.truncate().then(
() => console.log('Truncated collection'),
err => console.error('Failed to truncate:', err)
);
🔗 相關鏈接: