Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (19.9k points)

I'm doing a find on a nested array object and one of it's property. But the result is null.

i'm search for this object with the sub-object "externalAccounts" and it's extId 106100668938302013942.

This is my query:

  let user = await UserProfile.findOne({'externalAccounts': {$elemMatch: {extId: id}}});

Returning null. I also tried the externalAccounts.extId way but won't work as externalAccounts is an array. Any suggestions?

My Schemas:

const UserProfileSchema = new Schema(

externalAccounts:[{

          type: Schema.Types.ObjectId,

          ref: 'ExternalAccount',

          default: [],

        }]

}

const ExternalAccountSchema = new Schema(

        {

                type: { type: String },

                extId: { type: String },

                token: {type: String,},

        },

        {        usePushEach: true,}

    ); 

module.exports = Mongoose.model('ExternalAccount', ExternalAccountSchema);

1 Answer

0 votes
by (25.1k points)

The elemMatch is not working because the array contains a separate objectId/schema. I think it needs an aggregate.

So i remove the objectId and just make it an array of fields and now it works.

  externalAccounts:[{

          type: { type: String },

          extId: { type: String },

          token: {type: String,},

        }]

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...