[英]How to enable caching in ArangoDB via Docker or arangojs?
[英]How to store documents in an ArangoDb graph using ArangoJs?
我正在使用 nodejs 應用程序中最新版本的 ArangoDb 和 ArangoJs。 我有以下兩個頂點
tokens
頂點包含向users
頂點中的users
之一發行的安全令牌。 我有一個名為邊緣清晰度token_belongs_to
連接tokens
給users
如何使用 ArangoJs 存儲屬於現有用戶的新生成的令牌?
我將假設您將 ArangoDB 2.7 與最新版本的 arangojs(在撰寫本文時為 4.1)一起使用,因為自驅動程序的 3.x 版本以來 API 發生了一些變化。
由於您沒有提到使用Graph API ,最簡單的方法是直接使用集合。 但是,使用 Graph API 會增加一些好處,例如在刪除任何頂點時會自動刪除孤立邊。
首先,您需要獲得對要使用的每個集合的引用:
var users = db.collection('users');
var tokens = db.collection('tokens');
var edges = db.edgeCollection('token_belongs_to');
或者,如果您使用的是圖形 API:
var graph = db.graph('my_graph');
var users = graph.vertexCollection('users');
var tokens = graph.vertexCollection('tokens');
var edges = graph.edgeCollection('token_belongs_to');
為了為現有用戶創建令牌,您需要知道用戶的_id
。 文檔的_id
由集合名稱( users
)和文檔的_key
(例如12345678
)組成。
如果您沒有_id
或_key
您還可以通過其他一些唯一屬性查找文檔。 例如,如果您有一個知道其值的唯一屬性email
,則可以執行以下操作:
users.firstExample({email: 'admin@example.com'})
.then(function (doc) {
var userId = doc._id;
// more code goes here
});
接下來,您將要創建令牌:
tokens.save(tokenData)
.then(function (meta) {
var tokenId = meta._id;
// more code goes here
});
獲得 userId 和 tokenId 后,您可以創建邊來定義兩者之間的關系:
edges.save(edgeData, userId, tokenId)
.then(function (meta) {
var edgeId = meta._id;
// more code goes here
});
如果您不想在邊緣上存儲任何數據,您可以將一個空對象替換為edgeData
或簡單地將其寫為:
edges.save({_from: userId, _to: tokenId})
.then(...);
所以完整的例子會是這樣的:
var graph = db.graph('my_graph');
var users = graph.vertexCollection('users');
var tokens = graph.vertexCollection('tokens');
var edges = graph.edgeCollection('token_belongs_to');
Promise.all([
users.firstExample({email: 'admin@example.com'}),
tokens.save(tokenData)
])
.then(function (args) {
var userId = args[0]._id; // result from first promise
var tokenId = args[1]._id; // result from second promise
return edges.save({_from: userId, _to: tokenId});
})
.then(function (meta) {
var edgeId = meta._id;
// Edge has been created
})
.catch(function (err) {
console.error('Something went wrong:', err.stack);
});
注意 - 語法更改:
邊緣創建:
const { Database, CollectionType } = require('arangojs');
const db = new Database();
const collection = db.collection("collection_name");
if (!(await collection.exists())
await collection.create({ type: CollectionType.EDGE_COLLECTION });
await collection.save({_from: 'from_id', _to: 'to_id'});
https://arangodb.github.io/arangojs/7.1.0/interfaces/_collection_.edgecollection.html#create
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.