0

i have my schema as

const projectSchema = new mongoose.Schema({
name: {
    type: String,
    required:true,
},

auther: {
    type: String,
    required: true
},

discription: {
    type: String,
    required: true,
},
issues: [
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Issue'
    },

]
   }, { timestamps: true});

and my issue schema is

const issueSchema = new mongoose.Schema({
issue: {
    type: String,
    required:true,
},
auther: {
    type: String,
    required: true
},

discription: {
    type: String,
    required: true,
},
labels: [
    {
      type: String,
      trim: true,
      required: true,
    },
  ],

}, { timestamps: true });

i have stores obj id of issue in project and i want to search the issue by name in a specific project by its name of issue

eg issue: name: "developement" project.find(issues: name: "developement")

  • Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – rx2347 May 13 '23 at 14:13

1 Answers1

0
const projectName = 'example'; // replace with the project name you want to search
const issueName = 'issue1'; // replace with the name of the issue you want to find

const project = await Project.findOne({ name: projectName })
  .populate({
    path: 'issues',
    match: { issue: issueName },
    select: 'issue'
  })
  .exec();

if (project) {
  const issue = project.issues.find(issue => issue.issue === issueName);
  if (issue) {
    console.log(`Found issue '${issueName}' in project '${projectName}'`);
  } else {
    console.log(`Issue '${issueName}' not found in project '${projectName}'`);
  }
} else {
  console.log(`Project '${projectName}' not found`);
}

this is on aggregate mode with mongoose

Project.aggregate([
  { $match: { _id: mongoose.Types.ObjectId(projectId) } },
  {
    $lookup: {
      from: 'issues',
      localField: 'issues',
      foreignField: '_id',
      as: 'matchedIssues',
    },
  },
  {
    $match: { 'matchedIssues.issue': issueName },
  },
])
  .exec((err, results) => {
    if (err) {
      console.log(err);
    } else {
      console.log(results);
    }
  });

does this code help you?

bramasta vikana
  • 274
  • 1
  • 12