如何使用TypeDB Node.js客户端获取实体属性的实际值?
解决TypeDB Node.js客户端获取属性实际值的问题
你当前的核心问题是直接对属性Concept调用toString(),拿到的是它的ID字符串而非实际属性值。要获取真实值,必须先将Concept转为Attribute类型,再调用对应方法取值。
先梳理几个关键错误和修正点:
- 代码里
msTitle是笔误,应为mTitle checkAttribute.toString缺少括号,正确写法是checkAttribute.toString()- 获取属性值的正确流程:先用
isAttribute()确认是属性类型,再用asAttribute()转换,最后调用value()(TypeDB 2.x及以上版本用此方法,旧版本替换为getValue()即可)
修正后的完整代码示例:
export async function getMarketByTitle(title: string) { const database = "know_graph"; const { client, session, transaction } = await openTransaction(database); try { const query = ` match $m isa market, has title "${title}", has background_information $background_information; $m has title $m_title; get $m, $m_title, $background_information; `; const iterator = await transaction.query.match(query); let market; for await (const answer of iterator) { const mConcept = answer.get("m"); const mTitle = answer.get("m_title"); const backgroundInformation = answer.get("background_information"); const checkEntity = mConcept.isEntity(); const checkAttribute = mTitle.isAttribute(); // 修正属性值获取逻辑 const titleValue = checkAttribute ? mTitle.asAttribute().value() : null; const bgInfoValue = backgroundInformation.isAttribute() ? backgroundInformation.asAttribute().value() : null; market = { id: mConcept.toString(), title: titleValue, backgroundInformation: bgInfoValue, entity: checkEntity.toString(), attribute: checkAttribute.toString() }; return market; } } finally { // 务必关闭事务、会话和客户端,避免资源泄漏 await transaction.close(); await session.close(); await client.close(); } }
额外提醒:
- 必须在
finally块中关闭相关资源,防止长期占用连接 - 若使用TypeDB 1.x版本,将
value()替换为getValue()即可 - 可根据属性实际类型(字符串、整数、布尔等)添加类型断言,比如
titleValue as string
内容的提问来源于stack exchange,提问作者Captcha
相关产品推荐
相关产品推荐

