【发布时间】:2020-10-01 08:59:12
【问题描述】:
Graphql 查询在 mongodb 聚合后返回 id null(在前端),但如果我在解析器聚合中打印 console.log,_id 不为 null。我不知道为什么在后端我有一个 id 而前面是空的。任何人都可以帮助我吗?谢谢
客户端架构
const ClientSchema = mongoose.Schema({
surname: {
type: String,
require: true,
trim: true
},
company: {
type: String,
require: true,
trim: true
},
salesman: {
type: mongoose.Schema.Types.ObjectId,
require: true,
ref: 'User'
}
})
module.exports = mongoose.model('Client', ClientSchema)
订单架构
const OrderSchema = mongoose.Schema({
order: {
type: Array,
require: true,
},
total: {
type: Number,
require: true,
},
client: {
type: mongoose.Schema.Types.ObjectId,
require: true,
ref: 'Client'
},
salesman: {
type: mongoose.Schema.Types.ObjectId,
require: true,
ref: 'User'
},
stage: {
type: String,
default: "PENDENT"
},
})
module.exports = mongoose.model('Order', OrderSchema)
解析器
getOrdersBySalesman: async (_, { }, ctx) => {
const mongoObjectId = mongoose.Types.ObjectId(ctx.user.id);
try {
const orders = await Order.aggregate([
{ $match: { salesman: mongoObjectId }},
{ $lookup: {
localField: "client",
foreignField: "_id",
from: "clients",
as: "client"
}},
{ $unwind: '$client' },
{ $sort: { 'client.company': 1 }}
]);
console.log(orders);
return orders;
} catch (error) {
console.log(error);
}
}
Graphql 查询
const GET_ORDERS = gql`
query getOrdersBySalesman {
getOrdersBySalesman {
id
order{
name
quantity
}
total
client {
id
surname
company
}
stage
}
}`
结果console.log解析器_id很好
{ _id: 5ee0da703b683e071c0adfe2,
order: [ [Object] ],
stage: 'PENDENT',
total: 6166.65,
client:
{ _id: 5ea813b3085b4417b8627557,
surname: 'NOU2',
company: 'NN',
salesman: 5ea568905d47ed2760e8d11c,
__v: 0 },
salesman: 5ea568905d47ed2760e8d11c,
__v: 0 } ]
graphql 查询后的前端结果 id: null
{ id: null,
order: [{…}]
stage: 'PENDENT',
total: 6166.65,
client:
{ id: null,
surname: 'NOU2',
company: 'NN',
}
}
【问题讨论】:
-
id和_id是不同的字段吗?
-
id 和 _id 是相同的字段。 id 在前端(graphql 查询),_id 在后端(mongodb)。有2个id,一个是订单的id,第二个是客户的id
-
您似乎认为一个会自动翻译成另一个。我建议验证情况是否如此,并使用某种文档参考来更新您的问题,以证明这种期望。
-
medium.com/the-ideal-system/… - 最初它甚至是一个对象,而不是一个字符串
标签: node.js reactjs mongodb graphql