There is many question on that subject, but everything i could find and tried did not worked on my cases I have the following mongodb schema
var descSchema = new Schema({
name: {
type: "String"
},
base_name: {
type: "String"
},
type: {
type: "String"
},
size: {
type: "String"
}
});
var BaseSchema = new Schema({
base_name: {
type: "String",
unique: true
},
friendly_name: {
type: "String"
},
type: {
type: "String"
},
sizes: [
{
name: "String",
value: "String",
naming: descSchema
}
],
description: {
type: "String"
}
});
I need to find a document that match the base_name
(that works fine with db.find({base_name: myvariable}, function(err, element){...});
), but from that search I need to extract only the object naming
stored in the sizes
object array that match "name" = "myvalue"
of the previous searched document...
I did it with and map/indexOf but is not very elegant, and I am sure that there is a faster way to performed it
db.findOne({
base_name: "myname"
}, "sizes", function (err, element) {
var tmp = element.toObject();
var index = tmp.sizes.map(function (a) {
return a.name;
}).indexOf("myvalue");
console.log(tmp.sizes[index].naming);
});
below a sample of the collection:
[
{
_id: 5b76e89b7275781a484e3b14,
base_name: 'name1',
friendly_name: 'my geate name',
image_folder: 'img',
instruction_folder: 'notice',
fournitures_folder: 'fournitures',
type: 'standard',
cover: 'cover.jpg',
owner: 'owner.jpg',
sizes:
[
{
name: 'size01',
value: '48',
naming: {
name: 'Prototype_01',
base_name: 'Prototype_01',
friendly_name: 'Prototype PAC 01',
type: 'standard',
size: '48',
nb_item: 3,
items: [
...
]
}
},
{
name: 'size02',
value: '47',
naming: {
name: 'Prototype_02',
base_name: 'Prototype_02',
friendly_name: 'Prototype PAC 02',
type: 'standard',
size: '47',
nb_item: 3,
items: [
...
]
}
},
{
...
}
],
popularity: 5,
woo_id: '51'
},
{
...
}
]
And what I would like to retrieve if i requested the size 47
{
name: 'Prototype_02',
base_name: 'Prototype_02',
friendly_name: 'Prototype PAC 02',
type: 'standard',
size: '47',
nb_item: 3,
items: [
...
]
}