I have two collections: owners & plants. At the moment, every plant created has an owner assigned to it (plant.owner) . So if a user is logged in, and adds a plant, that plant has her/his ID added to the plant as an owner. But now, if I query that owner, I want to get a list of all plants he/she owns. In other words, all the plants in the plants collection that have plant.owner === owner._id.
But I am getting a little tangled in the logic. Can you tell me how to achieve this? This is what I have:
/models
const OwnerSchema = new mongoose.Schema(
{
userName: {type: String, required: true, },
plants: [{ type: mongoose.Schema.Types.ObjectId, ref: "Plant" }],
},
);
const PlantSchema = new mongoose.Schema(
{
commonName: { type: String, required: true, },
owner: { type: mongoose.Schema.Types.ObjectId, ref: "Owner" },
},
);
/typeDefs
type Plant {
id: ID!
commonName: String!
datePurchased: Date
substrate: Substrate
healthRating: Int
scientificName: String
familyName: String
public_id: String
owner: Owner
}
type Owner {
id: ID!
userName: String!
firstName: String
lastName: String
email: String
password: String
token: String
plants: [Plant!]
}
input PlantInput {
commonName: String!
public_id: String
owner: String!
}
type Mutation {
addPlant(plantInput: PlantInput): Plant
registerOwner(registerInput: RegisterInput): Owner
}
/resolvers/plantResolvers
Query: {
plants: async (obj, args, context) => {
const plants = await Plant.find().populate("owner");
return plants;
},
plant: async (obj, { id }, context) => {
return await Plant.findById(id);
console.log(error.message);
},
},
Mutation: {
addPlant: async (_, { plantInput: { commonName, owner } }) => {
const newPlant = await Plant.create({
commonName,
owner,
});
return newPlant.populate("owner");
},
},
// *** Embedded Objects Resolvers *** //
Plant: {
owner: (parent, args, context) => {
return Owner.findById(parent.owner);
},
},
/resolvers/ownerResolvers
// *** Query Resolvers *** //
Query: {
owners: async (obj, args, context) => {
return await Owner.find();
},
owner: async (obj, { id }, context) => {
return await Owner.findById(id);
console.log(error.message);
},
},
// *** Embedded Objects Resolvers *** //
Owner: {
plants: (parent, args) => {
# Is this where I should be looking to add plants to this document?
});
},
},
So I am confused as to whether the field plants (which should be a list of plant IDs) is populated upon the mutation addPlant(), or in the resolver for Owner: plants