Meteor grapher-react withQuery查询未返回正确结果
问题场景
我在使用grapher-react的withQuery方法拉取数据时,返回结果中creator关联字段仅包含少量字段,但数据库中creator对应的用户文档的profile字段下存储了远多于返回结果的字段,查询结果不符合预期。
基础查询定义
const userData = { _id: 1, profile: { firstName: 1, lastName: 1, phoneNumber: 1 }, shortName: 1, cookies: 1, } const tutorUserData = { _id: 1, profile: { headline: 1, hourlyRate: 1, firstName: 1, lastName: 1, croppedPicture: 1, tag: 1, currency: 1, subjects: 1, phoneNumber: 1 }, shortName: 1, cookies: 1, } export default Packages.createQuery('packages', { ownerId: 1, owner: userData, creatorId: 1, creator: tutorUserData, cost: 1, createdAt: 1, expiryDate: 1, currency: 1, values: 1, $filters: { expiryDate: { $gt: new Date() }, 'values.remainingMinutes': { $gt: 0 } }, $options: { sort: { createdAt: -1 } }, $filter({ filters, options, params }) { if (params.filters) { Object.keys(params.filters).forEach(key => { filters[key] = params.filters[key] }) } if (params.options) { Object.keys(params.options).forEach(key => { options[key] = params.options[key] }) } } })
withQuery调用逻辑
withQuery( ({ otherUser, user, params }) => { return query.clone({ ...params, filters: { $and: [{ ownerId: user._id }, { creatorId: otherUser._id }] }, options: { limit: 3, sort: { 'values.pending': -1, createdAt: -1 } } }) }, { reactive: true } )(Component)
问题根因
这是Grapher本身的查询规则导致的正常表现,不是程序异常:
- Grapher和MongoDB原生查询逻辑一致,采用白名单投影机制:只有在查询定义里明确指定要返回的字段,才会出现在最终结果中,没写在投影规则里的字段,就算数据库里存在存储也不会返回。
- 你定义的
tutorUserData中,creator.profile只声明了headline、hourlyRate、firstName等9个要返回的子字段,最终返回的creator.profile就只会包含这几个字段,其他存储在数据库中的profile子字段因为没被加入返回白名单,会被直接过滤。 - 如果需要返回
profile下的全量字段,不需要逐个罗列子字段,直接在tutorUserData里写profile: 1,就能拿到该字段下的所有存储数据。 - 如果已经把需要的字段都写在投影规则里还是返回不全,直接排查两个点:
- 确认
tutorUserData对象没有在其他代码逻辑中被修改,删掉了部分字段声明 - 检查服务端是否给这个查询配置了字段拦截逻辑(比如参数校验钩子、权限过滤规则),主动剔除了部分字段
- 确认
内容的提问来源于stack exchange,提问作者Ivan Liang
相关产品推荐
相关产品推荐

