简体   繁体   中英

Node.js find document by an element in array

I have a user schema with the following structure:

new Schema({
            email : String,
            password : String,
            shoppingCart : [{type : Schema.Types.ObjectId, ref : 'Product'}]
        });

and I also have a product schema as follows:

new Schema({
            title : String,
            description : String,
            vendorId : String,
            stock : Number
        });

How could I search for the users which have a specific product within their shopping carts? I tried both

UserModel.find({shoppingCart : product._id})...
and
UserModel.find({'shoppingCart._id' : product._id})....

but unfortunately it does not work. Any ideas? Thanks.

Have you tried...

UserModel.find({shoppingCart : product})

If you use the actual object within the query, it will hydrate itself into ID and runs the search based on that object ID.

Since you have a Schema type as "Schema.Types.ObjectId" if you run

UserModel.find({shoppingCart : product._id})

It will search against product._id as "String" not ObjectId.

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