Home > other >  MongoDb Query a One-To-Many Relationship
MongoDb Query a One-To-Many Relationship

Time:05-19

enter image description here

I have the following Documents, and I would like to return all the Organizations that a User belongs to, however I can't figure out the exact query I need to write?

I tried this, But I get an error

const organization = await Organization.find({ users: {$in: req.currentUser!.id} });
organization.ts(13, 3): The expected type comes from property 'users' which is declared here on type 'FilterQuery<OrganizationDoc>'

Model for Organization


import mongoose from "mongoose";
import { updateIfCurrentPlugin } from "mongoose-update-if-current";
import { UserDoc } from "./user";
import { PlanDoc } from "./plan";
interface OrganizationAttrs {
  name: string;
  users: UserDoc[];
  plan: PlanDoc;
}

interface OrganizationDoc extends mongoose.Document {
  name: string;
  users: UserDoc[];
  plan: PlanDoc;
  version: number;
}

interface OrganizationModel extends mongoose.Model<OrganizationDoc> {
  build(attrs: OrganizationAttrs): OrganizationDoc;
}

const organizationSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    users: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    ],
    plan: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Plan",
    },
  },
  {
    toJSON: {
      transform(doc, ret) {
        ret.id = ret._id;
        delete ret._id;
      },
    },
  }
);
organizationSchema.set("versionKey", "version");
organizationSchema.plugin(updateIfCurrentPlugin);

organizationSchema.statics.build = (attrs: OrganizationAttrs) => {
  return new Organization(attrs);
};

const Organization = mongoose.model<OrganizationDoc, OrganizationModel>(
  "Organization",
  organizationSchema
);

export { Organization };

I think the issue is that users is an array of UserDoc types?

CodePudding user response:

well you can do that with javascript but in typescript, $in request an Array so you can easy fixed it by put userId to array

const organization = await Organization.find({ users: {$in: [req.currentUser.id]} });

CodePudding user response:

Because users is an array of UserDoc. first find the user then query Organization by the user that you found.

import express, { Request, Response } from "express";
import { Organization } from "../models/organization";
import { User } from "../models/user";

const router = express.Router();

router.get("/api/organization", async (req: Request, res: Response) => {
  const user = await User.findById(req.currentUser!.id);
  if (user) {
    const organization = await Organization.find({ users: user });
    res.send(organization);
  }
});

export { router as indexOrganizationRouter };

  • Related