Graphql为猫鼬聚合查询返回空ID [英] Graphql returns null id for mongoose aggregation query
问题描述
Graphql为猫鼬聚合查询返回空ID,但在其他猫鼬查询中也可以使用.
Graphql returns null id for mongoose aggregation query, but works ok other mongoose queries.
这是我的猫鼬图式:
const { Schema } = mongoose;
const ObjectId = Schema.Types.ObjectId;
const productSchema = new Schema({
_id: ObjectId,
price: Number
})
const Product = mongoose.model('Product', productSchema, 'Product')
这是我的Graphql模式:
Here is my Graphql schema:
type Product {
id: ID
price: String
}
Graphql常规查询:
Graphql normal query:
context.Product.findOne()
console.log的结果:
Result with console.log:
[ {
price: 10,
_id: 5d7f8efebff791dcd3bb1b69
}]
graphql的结果:
Result with graphql:
"getSearch": [
{
"id": "5d7f8efebff791dcd3bb1b69",
"price": 10,
}]
这里一切都很好. 现在问题在于聚合查询:
GraphQL查询:
GraphQL query:
context.Product.aggregate(
[
{ $sample: { size: 1 } }
]
)
console.log的结果:
Result with console.log:
[ { _id: 5d7f8f23bff791dcd3bb1da3,
price: 5
}]
使用GraphQL的结果:
Result with GraphQL:
"test": [
{
"id": null",
"price": 7,
}]
这里的问题是:
- id为空
- console.log和graphql的响应是不同的对象
推荐答案
MongoDB中的文档通常没有id
属性,只有一个_id
属性.这显示在您看到的控制台输出中.但是,猫鼬模型实例确实具有id
的吸气剂,该吸气剂返回id
的值. 从文档中:
Documents in MongoDB normally don't have an id
property, just an _id
property. This is shown in the console output you're seeing. However, mongoose model instances do have a getter for id
that returns the value of id
. From the docs:
猫鼬默认情况下为您的每个模式分配一个id虚拟获取器,该返回器将文档_id字段强制转换为字符串,如果是ObjectIds,则返回其hexString.
Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.
find
和findOne
之类的方法返回的是模型的实例一个>有这个吸气剂.但是,使用aggregate
会导致返回纯JavaScript对象(没有getter).
What's returned by methods like find
and findOne
are instances of the Model that have this getter. However, using aggregate
results in plain JavaScript objects being returned instead (with no getter).
您可以为id
字段编写一个解析程序,以从id
或_id
提取值:
You can write a resolver for the id
field to pull the value from either id
or _id
:
function resolve (parent, args, context, info) {
return parent.id || parent._id
}
这篇关于Graphql为猫鼬聚合查询返回空ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!