MongoDB / Mongoose:为什么不填充聚会的hostedBy字段?

时间:2019-06-21 13:33:04

标签: javascript node.js mongodb mongoose graphql

从数据库中获取(或创建和获取)保存的聚会时,为什么没有填充引用用户模型的hostedBy字段?相反,addedBy字段恰好在返回值(meetup)上填充。那有什么呢?

下面是相关的代码段。

请不要为了避免冗长而剥离代码。

Meupup猫鼬模式

import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const MeetupSchema = new Schema(
  {
    addedBy: { type: Schema.Types.ObjectId, ref: 'User' },
    type: { type: [String] },
    details: { 
      name: { type: String },
      hostedBy: { type: Schema.Types.ObjectId, ref: 'User' },
      description: { type: String },
      imageUrl: { type: String },
      eventStart: { type: Date },
      eventEnd: { type: Date },
    },
  },
  {
    timestamps: true,
  }
);

MeetupSchema.virtual('id').get(function () {
  return this._id.toString();
});

export default mongoose.model('Meetup', MeetupSchema);

用户猫鼬模式

import bcrypt from 'bcryptjs';
import mongoose from 'mongoose';
import validator from 'validator';

const Schema = mongoose.Schema;

const UserSchema = new Schema({
  firstname: { type: String },
  lastname: { type: String },
  email: {
    type: String,
    lowercase: true, 
    trim: true, 
    index: true,
    unique: true,
    sparse: true,
    validate: value => validator.isEmail(value),
  },
  password: { type: String },
},
{
    timestamps: true,
});

// Convert type of _id to (id) string
UserSchema.virtual('id').get(function() {
  return this._id.toString();
});

// Return fullname
UserSchema.virtual('fullname').get(function() {
  return this.firstname + ' ' + this.lastname;
});

UserSchema.virtual('fullname').set(function(name) {
  const str = name.split(' ');

  this.firstname = str[0];
  this.lastname = str[1];
});

const User = mongoose.model('User', UserSchema);

export default User;

创建Meetup解析器

import { combineResolvers } from "graphql-resolvers";

import { isAuthenticated, isMeetupCreator } from "./authorization";

export default {
  Mutation: {
    createMeetup: combineResolvers(
      isAuthenticated,
      async (parent, args, { models: { Meetup } }, info) => {
        try {
          // Create and save new meetup to DB
          let newMeetup = await Meetup.create(args);

          newMeetup = await newMeetup
            .populate({
              select: "id type details location addedBy",
              populate: [
                {
                  path: "addedBy",
                  select: "fullname id"
                },
                {
                  path: "details.hostedBy",
                  select: "fullname email id"
                }
              ]
            })
            .execPopulate();

          return newMeetup;
        } catch (error) {
          throw new Error(error.message);
        }
      }
    ),
  }
};

Meetup GraphQL架构

import { gql } from 'apollo-server-express';

export default gql`
  type MeetupLocation {
    name: String!
    longitude: Float!
    latitude: Float!
  }

  type MeetupDetails {
    name: String!
    hostedBy: User!
    description: String!
    imageUrl: String!
    eventStart: Date!
    eventEnd: Date!
  }

  type Meetup {
    id: ID!
    addedBy: User!
    type: [String!]!
    location: MeetupLocation!
    details: MeetupDetails!
    photos: [String]
    attendees: [User]!
    comments: [Comment]!
    createdAt: Date!
    updatedAt: Date!
  }

  input MeetupLocationInput {
    name: String!
    longitude: Float!
    latitude: Float!
  }

  input MeetupDetailsInput {
    name: String!
    hostedBy: String!
    description: String!
    imageUrl: String!
    eventStart: Date!
    eventEnd: Date!
  }

  extend type Mutation {
    createMeetup(
      addedBy: ID!
        location: MeetupLocationInput!, 
      type: [String!]!, 
        details: MeetupDetailsInput!, 
    ): Meetup!
  }
`;

用户GraphQL架构

import { gql } from 'apollo-server-express';

export default gql`
  type User {
    id: ID!
    fullname: String!
    firstname: String!
    lastname: String!
    email: String!
    addedMeetups: [Meetup]!
    hostedMeetups: [Meetup]!
    attendedMeetups: [Meetup]!
    attending: [Meetup]!
  }

  extend type Query {
    allUsers: [User]!
    userById(userId: ID!): User!
    currentUser: User!
  }
`;

0 个答案:

没有答案