简体   繁体   中英

Mongoose find one query on object under object

I have user schema

var userSchema = new Schema({
     userId          : {type:String,default:'',required:true},
    firstName       : {type:String,default:'',required:true}, 
    lastName        : {type:String,default:'',required:true}, 
    email           : {type:String,default:'',required:true},
    password        : {type:String,default:'',required:true}, 
    mobileNumbers   : {}, 
    recoveryDetails : {}, 
    walletInfo      : {}, 
    savedAddress    : {}, 
    savedCards      : {}, 
    cart            : {
        productId              :  {type:String,default:'',required:true},
        productName            :  {type:String,default:'',required:true}, 
        productPrice           :  {type:String,default:'',required:true},
        productDescription     :  {type:String,default:'',required:true},
        productSpecifications  :  {}, 
        productSeller          :  {}, 
        productImages          :  [], // An array to store product images //
        productCategory        :  []  // Product categories array //

    }   // Shopping cart array of user //
});

I want to find product with product ID. I am writing query like

  userModel.findOne({'user.cart': {$elemMatch: {productId: productsId}}},function(err,productFoundInUserCart){
});

Is this Correct way ? Not working on my side. Can anyone help me on this ?

Your query is wrong, try this

userModel.findOne({'cart.productId': productsId},function(err,productFoundInUserCart){
});

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