kapsztat12
kapsztat12

Reputation: 85

How to get element property from array in Mongoose?

I have document structure like this in my schools collection MongoDB document

I am searching school by its code from array of codes School.findOne({ 'codes.code': '12345678' }) and I am getting my school but I also want to get code.type property from code object where my code is 12345678. Should i use javascript Array.find?

Upvotes: 0

Views: 147

Answers (1)

metaphori
metaphori

Reputation: 2811

What you can do is selecting the matching array element by

School.find({ 'codes.code': '12345678' }, {"codes.$":1})

Otherwise, yes, you need to find the element in the array:

var myschool = School.find({ 'codes.code': '12345678' })[0]
myschool.codes.find(c => c.code == '12345678')

Upvotes: 1

Related Questions