1
    var mongoose = require("mongoose");
    
    // schema setup
    var productSchema = new mongoose.Schema({
        type:{
            type:String,
            required:[true,'a product must have a type']
        },
        sId:String,
        image:String,
        products:[{
            name:String,
            image:String,
            price:Number
        }]
    });
    
    module.exports = mongoose.model("Product",productSchema);

I have made my mongoose schema like this. Now I just want to access a particular object from the array of objects named 'products' using a mongoose query. Can anyone please tell me how can i do this?? I'll be soo grateful.

1 Answer 1

1

You need something like this:

db.collection.find({
  "products.name": "name"
},
{
  "products.$": 1
})

With this query you will find the product object whose name field is 'name'. Afther that, with the positional operator $ only the matching is returning.

Mongo playground example here

Edit: Note that this query will return multiple subdocuments if exists multiple documents with the array object matching. To filter for a unique element you have to indicate another unique field like this:

db.collection.find({
  "sId": "1",
  "products.name": "name"
},
{
  "products.$": 1
})

Edit to explain how to use find using mongoose.

You can use find or findOne, but the query itself will be the same.

This is pretty simple. You need to use your model described in the question, so the code is somthing like this:

var objectFound = await YourModel.findOne({
  "products.name": "name"
},
{
  "products.$": 1
})

Where YourModel is the schema defined.

Sign up to request clarification or add additional context in comments.

2 Comments

Thankyou so much for the answer.But what you told me will only work in the console.What would be the mongoose query for it..to directly add in the code???
@ShagunSharma I've updated the answer. But, basically the query itself is the same into mongoose. You have to call findOne() function from your model.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.