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?
2
Answers
Because
users
is an array ofUserDoc
. first find the user then query Organization by the user that you found.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