Graphql mongodb 无法返回 _id
Posted
技术标签:
【中文标题】Graphql mongodb 无法返回 _id【英文标题】:Graphql mongodb cannot return _id 【发布时间】:2021-02-25 09:42:48 【问题描述】:大家好,我正在使用 graphql 和 mongodb 创建一个 api。我正在使用 mongodb 聚合来过滤我的文档。
export const findAllVariants = async (_, orderby, filter, skip, sort, perPage , context) =>
await jwtAuthentication.verifyTokenMiddleware(context);
try
const aggregate = Variant.aggregate();
const match = $and: [] ;
if (filter)
await filter.split(' ').forEach((f) =>
match.$and.push(
$or: [
color:
$regex: new RegExp(transliterate(f), 'i')
,
size:
$regex: new RegExp(transliterate(f), 'i')
,
sku:
$regex: new RegExp(transliterate(f), 'i')
,
barcode:
$regex: new RegExp(transliterate(f), 'i')
]
);
);
aggregate.match(match);
const options =
allowDiskUse: true,
limit: perPage,
page: skip,
sortBy: [orderby]: sort
;
return Variant.aggregatePaginate(aggregate, options, (err, results, pageCount, count) =>
if (err)
return new ApolloError(`There was an error $err`);
console.log(results);
return
count,
variants: results,
pageCount,
skip
;
);
catch (err)
return new ApolloError(`There was an error $err`);
;
我的graphql def是这个
export default gql`
type VariantsResult
variants: [Variant]
count: Int
pageCount: Int
skip: Int
type Variant
id: String!
color: String
size: String
quantity: Int
sku: String
barcode: String
price: Price
images: [String]
input VariantInfo
id: ID!
color: String!
size: String!
quantity: Int
sku: String!
barcode: String!
price: InputPrice!
images: [ImageInfo]!
extend type Query
findAllVariants(orderby: Int, filter: String, skip: Int, sort: Int, perPage: Int): VariantsResult
extend type Mutation
createVariant(variantInfo: VariantInfo): Variant!
removeVariantFromProduct(variantInfo: VariantInfo, productInfo: ProductInfo): Product!
addVariantToProduct(variantInfo: VariantInfo, productInfo: ProductInfo): Product!
editVariantFromProduct(variantInfo: VariantInfo): Variant!
`;
现在在阿波罗操场上,当我提供所需的数据并返回 id 值时,它会显示以下消息“无法为不可为空的字段 Variant.id 返回 null。”
这仅发生在 id 字段中,所有其他字段都可以正常工作。 请帮忙!
【问题讨论】:
【参考方案1】:错误:
身份证!表示该字段不可为空 (https://graphql.org/learn/schema/):
id: ID!
在您的情况下,Variant.id
为 null(抛出错误)。
在 GraphQL 中使用可空性:https://www.apollographql.com/blog/using-nullability-in-graphql-2254f84c4ed7/
可能的解决方案:
Mongodb 使用_id
而不是id
类型可以是:
type Player
_id: String
name: String
salary: String
通过 id 获取数据可能如下所示 (ObjectID docs):
db.collection('baseballPlayers').findOne( _id: ObjectID("5faeda2c7e348a5e142827ae") );
或compass:
Sum: 从简单的 Query by id 开始(在你进入聚合之前)并检查返回值是否为 null(或不是)。然后在 _id 字段解析器中使用正确的查询。
相关问题:
How do I search for an object by its ObjectId in the mongo console?相关教程:
https://medium.com/the-ideal-system/graphql-and-mongodb-a-quick-example-34643e637e49【讨论】:
以上是关于Graphql mongodb 无法返回 _id的主要内容,如果未能解决你的问题,请参考以下文章
Mongodb graphQL和Feather js数据通过_id获取在某些情况下返回null