Meteor and Mongo DB give different results when doing findOne () on an array
I have a collection with an array of objects in it (I just laid out some fields from it, the schema works fine).
Contact collection:
title: {
type: String,
label: "Title",
max: 200
},
adresses: {
type: [Object],
optional: true
},
"adresses.$.id": {
type: String,
label: "ID"
},
"adresses.$.street": {
type: String,
label: "street",
decimal: true,
optional: true
}
When I do a:
db.contacts.findOne({_id: "59gXADmH9GLNDjELo"}, {adresses: {$elemMatch:
{id: "xpdYRKGGjHJLnCevM"}}});
in Mongo DB console, it returns:
{
"_id" : "59gXADmH9GLNDjELo",
"adresses" : [
{
"id" : "xpdYRKGGjHJLnCevM",
"street" : "FakeStreet123"
}
]
}
As I want it is just one element of the array.
When I do the same in Meteor (Browser Console):
Contacts.findOne({_id: "59gXADmH9GLNDjELo"}, {adresses: {$elemMatch:
{id: "xpdYRKGGjHJLnCevM"}}});
I am returning all the elements of the array. How to solve this? I want to get the same result as in Mongo DB.
+3
source to share
1 answer
You can use the underscore method to get just the document you want: ._find()
var doc = Contacts.findOne(
{_id: "59gXADmH9GLNDjELo"},
{adresses: {
$elemMatch: {id: "xpdYRKGGjHJLnCevM"}
}
}),
address = _.find(doc.adresses, function(address) {
return address._id === "xpdYRKGGjHJLnCevM"
});
+2
source to share