You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Velo中如何从后端获取当前用户ID并用于客户端查询匹配帖子所有者

问题分析

你的核心问题是异步函数的执行顺序错误:myGetCurrentMemberFunction()是异步函数,返回的是Promise对象,而wixData.query().eq()方法需要的是实际的用户ID字符串。你直接把Promise传给eq(),导致查询条件不生效,自然拿不到正确的结果。

修正方案

方案一:使用Promise链式调用(then嵌套)

先等待后端返回用户ID,再基于ID执行数据查询:

import { myGetCurrentMemberFunction } from 'backend/backendfunctions.jsw'

function matchPostCurrentUser(event) {
  // 先获取当前用户ID,再执行查询逻辑
  myGetCurrentMemberFunction()
    .then(memberId => {
      console.log(memberId);
      // 拿到有效ID后构建查询
      return wixData.query("Collection1")
        .eq("_owner", memberId)
        .find();
    })
    .then(results => {
      const result = results.items;
      console.log(result);
      if (result.length === 0) {
        console.log("你选择的是其他用户的帖子ID");
      }
    })
    .catch(error => {
      console.error("获取用户ID或查询数据失败:", error);
    });
}

方案二:使用async/await(代码更简洁)

用async/await处理异步逻辑,让代码顺序更直观:

import { myGetCurrentMemberFunction } from 'backend/backendfunctions.jsw'

async function matchPostCurrentUser(event) {
  try {
    // 等待获取用户ID
    const memberId = await myGetCurrentMemberFunction();
    console.log(memberId);
    
    // 执行数据查询
    const results = await wixData.query("Collection1")
      .eq("_owner", memberId)
      .find();
      
    const result = results.items;
    console.log(result);
    if (result.length === 0) {
      console.log("你选择的是其他用户的帖子ID");
    }
  } catch (error) {
    console.error("获取用户ID或查询数据失败:", error);
  }
}
后端代码优化(可选)

你的后端代码可以简化,直接返回用户ID:

import { currentMember } from 'wix-members-backend';

export async function myGetCurrentMemberFunction() {
  const member = await currentMember.getMember();
  return member._id;
}

内容的提问来源于stack exchange,提问作者Al.Y

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:15:12