'How to find whether particular element exist in array of object or not in mongodb

My database schema looks like below:

import mongoose, { Schema, Document } from 'mongoose';

export interface ITeam extends Document {

  email: string;

  name: string;

  role: boolean;

  status: string;

}

export interface IAdmin extends Document {

  adminEmail: string;

  adminName: string;

  teamMate: Array<ITeam>[];

}

const TeamSchema = new Schema({

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

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

  role: { type: Boolean, required: true },

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

});

const AdminSchema = new Schema({

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

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

  teamMate: [TeamSchema],

});

export default mongoose.model<IAdmin>('Admin', AdminSchema);

In db it is:

_id:61ec9cbd2beb5b236d9035f4

    teamMate  :

    Array
        0  :Object
            name:"neha"
            role :true
            status:"inActive"
            email:"[email protected]"
        1 : Object
            name :"xyz"
            role :true
            status :"inActive"
            email :"[email protected]"
    adminEmail :"[email protected]"
    adminName :"abc"

I have tried this:

 const teamMember: Array<ITeam> = req.body.teamMate;

 const t= teamMember.map(x=> x.email)

   t.forEach((x)=>{

   const l= AdminModel.find({teamMate:{elemMatch:{email:x.email}}})
 })

this line showing error:

const l= AdminModel.find({teamMate:{elemMatch:{email:x.email}}})

I want to check whether particular("[email protected]") email exist or not, If yes then don't add it to Database. I don't want to do it with index wise as it is not confirm how many teamMate will be there.

Thanks in Advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source