简体   繁体   中英

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
              }
          ]
      }
  }
});

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}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM