Shagun Sharma
Shagun Sharma

Reputation: 19

How will I select a particular object from the array of objects in the mongoose schema?

    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.

Upvotes: 1

Views: 738

Answers (1)

J.F.
J.F.

Reputation: 15235

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.

Upvotes: 1

Related Questions