How do i take a mongoose model out of an array that is within another mongoose model?

Viewed 28

Okay so i have 2 schemas from mongoose, a model schema and a diagram schema.

Model.ts

import mongoose, {Schema} from 'mongoose';
import { Diagram} from "./index";

const modelSchema = new mongoose.Schema({
    email: String,
    name: String,
    diagram: [{type: Schema.Types.ObjectId, ref: 'Diagram'}]
})

const Model = mongoose.model('Model', modelSchema);
export default Model

Diagram.ts

import mongoose from 'mongoose';

const diagramSchema = new mongoose.Schema({
    name: String,
    info: String,
    version: Number,
    diagram: String
})

const Diagram = mongoose.model('Diagram', diagramSchema)
export default Diagram

As seen in my Model.ts, my model uses an array made from diagrams and i want to be able to find my schema diagram within that array. But i don't know how. I've already tried to find the diagram using Model.findOne() but that needs the ID of the schema whereas i want to search for it using the diagram name. How do i do that?

1 Answers

After a lot of trying, searching and pulling my hair out i managed to find a solution which was surprisingly a lot easier than i thought.

const diagram = await Model.find({name:modelname}).populate({
    path: 'diagram',
    match: {name: diagramname}
});
Related