在尝试从MongoDB检索文档时,我遇到了一个看似微不足道的问题,但仍然存在。我将Mongoose用作ODM,但在提取符合特定条件的文档时遇到了麻烦。我看过类似的问题/问题,但似乎没有建议对我有用。
下面是涉及获取与特定位置名称匹配的聚会对象的示例的片段。
export default {
Query: {
//...
meetupsByLocation: async (parent, { location }, { Meetup }, info) => {
try {
const meetups = await Meetup.find({
"location.name": { "$eq" : location, "$exists" : true }
});
// Tried this one too but to no avail
//const meetups = await Meetup.find({ "location.name": location });
return meetups.map(meetup => {
meetup._id = meetup._id.toString();
return meetup;
});
} catch (error) {
throw new Error(error.message);
}
}
//...
},
Mutations: {
//...
},
};
Meetup GraphQL架构
export default `
scalar DateTime
type MeetupLocation {
name: String!
longitude: Float!
latitude: Float!
}
type MeetupDetails {
name: String!
hostedBy: String!
description: String!
imageUrl: String!
eventStart: DateTime!
eventEnd: DateTime!
}
type Meetup {
id: ID!
addedBy: String!
type: [String!]!
location: MeetupLocation!
details: MeetupDetails!
photos: [String]!
attendees: [String]!
comments: [String]!
}
# Queries
type Query {
meetupsByLocation(location: String!): [Meetup]!
}
`
Meupup猫鼬模式
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const MeetupSchema = new Schema(
{
addedBy: { type: Schema.Types.ObjectId, ref: 'User' },
type: { type: [String] },
location: {
name: { type: String },
longitude: { type: Number },
latitude: { type: Number },
},
details: {
name: { type: String },
hostedBy: { type: Schema.Types.ObjectId, ref: 'User' },
description: { type: String },
imageUrl: { type: String },
eventStart: { type: Date },
eventEnd: { type: Date },
},
photos: { type: [String] },
attendees: [{ type: Schema.Types.ObjectId, ref: 'User' }],
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }],
},
{
timestamps: true,
}
);
export default mongoose.model('Meetup', MeetupSchema);
NB :已编辑以包含架构。