Pentico Pentico - 8 days ago 5
Node.js Question

I am trying to get a single array value from mongodb, but when i try i get the whole object

1.I Don't get the Item in Electro Array but the whole doc

getItem(data){
dbswap.findOne(
{ 'swap.Items.Electro.id':data.id,
'swap.Items.Electro.id':data.id }, function(err,item){
if(err){
return (err);
}
if(item){
console.log(item);
}

});
} // EOF



This is my Schema

1.I am trying to get the item i create in Electro only, I don't want the whole object i am getting at the moment.


var swapSchema = new mongoose.Schema({
swap: {
name: String,
Items: {
Electro: [
{
name: String,
info: String,
price: Number,
dateCreated: Date,
category: String,
id: Number
}
]
}
}
});

Answer

Use the projection field :

If you want to get all the array :

   dbswap.findOne(
    { 'swap.Items.Electro.id':data.id},
    { 'swap.Items.Electro' : 1}
   , function(err, obj){

will return something like :

{
 _id: ObjectId("sdfsdfsdf"),
 Electro:[{....},{....}]
}

Or if you want only the object in the array who match the query :

   dbswap.findOne(
    { 'swap.Items.Electro.id':data.id},
    { 'swap.Items.Electro.$' : 1}
   , function(err, obj){

will return something like :

{
 _id: ObjectId("sdfsdfsdf"),
 Electro:{your match object}
}