0

This is my schema

var Schema = new Schema{
     name:String
     topics:[{item:{type: ObjectId, ref: 'tag'},comment:String}]
}

So 'topics' field contains an array of embedded docs. Each of those contains a ref and a string 'comment'. There is a way I can find a specific ref id (the item field)?

I tried some projection but this make some sense don't you think? Obiouvsly doesn't work..:)

    Model
    .find(
        { topics: {
            $in: [{     item: ObjectId("56e0aa684e7c55c414a51d82")      }]
        }
        },{name:1})
    .exec(function(err, data) {
        res.json(data)
    });

EDIT: I came up with this solution:

           Model
            .find(
                {'topics':
                    {$elemMatch :
                        {
                            item: "56e0aa684e7c55c414a51d82"
                        }
                    }
                }
            )
    .exec(function(err, data) {
        res.json(data)
    });

1 Answer 1

1

Please try this one

Model.find({'topics.item': "56e916772acfbbf805612555"}, {name: 1})
    .exec(function(err, data){
        if (err)
            console.log(err);
        else
            console.log(data);
    });

Test with data

{ "_id" : ObjectId("56e916772acfbbf805612559"), 
  "name" : "topic1", 
  "topics" : [
          { "item" : ObjectId("56e916772acfbbf805612555"), 
            "comment" : "tag1", 
            "_id" : ObjectId("56e916772acfbbf80561255b") }, 
          { "item" : ObjectId("56e916772acfbbf805612556"), 
            "comment" : "tag2", 
            "_id" : ObjectId("56e916772acfbbf80561255c") } ]
}

Return

[ { name: 'topic1', _id: 56e916772acfbbf805612559 } ]
Sign up to request clarification or add additional context in comments.

3 Comments

thanks! please refer to my edit too, what's do you think is the better? The strange part of my solution is if I cast to ObjectId: item: mongoose.Schema.Types.ObjectId("56e0aa684e7c55c414a51d82") I get wrong results!
@the.websurfer, per this doc, Since the $elemMatch only specifies a single condition, the $elemMatch expression is not necessary, and instead you can use the following query: db.survey.find( { "results.product": "xyz" } )
@the.websurfer, you do not need to cast to ObjectId...in your wrong case.

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.