【发布时间】:2020-08-27 05:13:57
【问题描述】:
大家好,我在这里使用的是带有 mongoose 和 nodejs 的 graphql,所以我的架构是这样的
booking.js
const mogoose = require("mongoose");
const autopopulate = require('mongoose-autopopulate')
const Schema = mogoose.Schema;
const bookingSchema = new Schema({
event:{
type:Schema.Types.ObjectId,
ref:'Event',
autopopulate:true
},
},{timestamps:true});
module.exports=mogoose.model('Booking',bookingSchema.plugin(autopopulate))
event.js
const mogoose = require("mongoose");
const autopopulate = require('mongoose-autopopulate')
const Schema = mogoose.Schema;
const eventSchema = new Schema({
title: {
type: String,
},
description: {
type: String,
},
price: {
type: Number,
},
date: {
type: String,
required: true,
},
creator:{
type:Schema.Types.ObjectId,
ref:'User',
autopopulate:true
}
});
module.exports=mogoose.model('Event',eventSchema.plugin(autopopulate))
然后在我的解析器中删除一个事件,我做了这样的事情
cancelEvent: async (args) => {
try {
const booking = await Booking.findById(args.bookingID);
const event={...booking.event,_id:booking.event._id}
await Booking.deleteOne({ _id: args.bookingID });
return event
} catch (err) {
throw err;
}
},
console.log(event._doc) 给我
{ _id: 5eb94b2ee627fc04777835d2,
title: '22222',
description: 'sd',
date: 'df',
creator:
{ createdEvents:
[ [Object], [Object], [Object], [Object], [Object], [Object] ],
_id: 5eb80367c2483e16a9e86502,
email: 'sdd',
password:
'$2a$12$3lNyWl8w9gWLo8TtJDL2Te6Wg6psQOrOveinifFF4Jjeij9b4P2Ga',
__v: 16 },
__v: 0 }
所以可以说我的数据库是这样的
_id:ObjectId("5eb96b75c43aca45ff6aa934")
user:ObjectId("5eb80367c2483e16a9e86502")
event:ObjectId("5eb94b2ee627fc04777835d2")
createdAt:"2020-05-11T14:42:22.470+00:00"
updatedAt:"2020-05-11T14:42:22.470+00:00"
__v:"0"
然后我写了我的graphql查询
mutation{
cancelEvent(bookingID:"5eb96b75c43aca45ff6aa934"){
_id,
event{
title
}
}
}
我得到的结果是
{
"data": {
"cancelEvent": {
"_id": "5eb94b2ee627fc04777835d2",
"event": null
}
}
}
id 是我在解析器中返回的事件,但事件标题为空, 即使我尝试过
mutation{
cancelEvent(bookingID:"5eb96b75c43aca45ff6aa934"){
title
}
}
它说
无法查询类型 Booking 的字段标题
那么我如何获取与刚刚删除的预订相关的事件的标题?
【问题讨论】:
标签: node.js mongodb mongoose graphql graphql-js