1
var CarSchema = new Schema({
    name: {type: String},
    partIds: [{type: Schema.Types.ObjectId, ref: 'Part'}],
});

var PartSchema = new Schema({
    name: {type: String},
    props: [
        { colour: {type: String}, shape: {type:String} }
    ],
});

For example

Car = {
       name: "BMW",
       partIds:[ObjectId("57baa43e152654f80aac36a6")]}

Part = {
        _id: ObjectId("57baa43e152654f80aac36a6"),
        name: "Piston",
        props: [{colour:"red", shape: "Cubical"},{colour:"green", shape: "cylindrical"}]

So when I query I should get a doc like this:

Car = {
      name: "BMW",
      partIds: [{ 
_id:ObjectId("57baa43e152654f80aac36a6"), name:"Piston", props: [{colour:"red", shape:"cubical"}]
     }

The props array should only have element with colour red

I want to populate Car with Part Array such that its prop array only have the object with colour red. Is there anyway to do it, or would I have to go old fashioned way and loop through props array matching its colour with red.

5
  • Do you already have the part Collection? Or do you create it and store its id in car Collection? Commented Aug 25, 2016 at 7:47
  • Part collection is different and its Ids are stored in Car collections' partIds Commented Aug 25, 2016 at 7:49
  • so you want to create part document and store its id in car collection if the color is red? Commented Aug 25, 2016 at 8:32
  • No, I want to query the Car collection such that it populate partIds such that props aray only have elements whose colour is red. Commented Aug 25, 2016 at 8:44
  • 1
    Added sample docs Commented Aug 26, 2016 at 9:52

2 Answers 2

1

You can do this by providing the select option in your populate call:

Car.findOne()
    .populate({
        path: 'partIds',
        select: { props: { $elemMatch: { colour: 'red' } }, name: 1 }
    })
    .exec(callback);

Result:

{ _id: 57c085451cd8dfcdf814f640,
    name: 'BMW',
    partIds:
     [ { _id: 57baa43e152654f80aac36a6,
         name: 'Piston',
         props: [ { colour: 'red', shape: 'Cubical' } ] } ] }

The select uses the $elemMatch projection operator to select just the red props element.

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

Comments

0

you can try this, it should get you what you want.

car.find({"partIds.props.colour" : "red"})
    .populate('partIds')
    .exec(function(err,result){...});

Comments

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.