$elemMatch (projection ) does not work with dbref #1091

Closed
skotchio opened this Issue Sep 5, 2012 · 5 comments

Projects

None yet

2 participants

@skotchio
skotchio commented Sep 5, 2012

My question is releated to #1085 I've found that $elemMatch doesn't work with dbref. Say I have the following a parent and a child schemas:

 var commentSchema = new Schema({
   content: [String]
});

var postSchema = new Schema({
   comments: [{type: Schema.ObjectId, ref: 'Comment'}]
});

If do such as in previous issue but with comments then I'm don't getting desired result:

Post.findOne({ _id: post_id })
     .select({ comments: { $elemMatch: {$in: ['50478c35889a450000000001', '50478c35889a450000000002'] }}})
     .exec(function (err, doc) {
         console.log(doc.comments); // empty []
         done(err);
});

In the code above I get empty array. I'm expected to get an array of comment ids.
P.S: I know I could be using an .populate() but I don't need a model instances, I need a only id's

@aheckmann
Collaborator

field projections are not yet casted. for now the work-around is to first cast your strings to objectids:

var ObjectId = mongoose.Types.ObjectId;
var ids = [new ObjectId('50478c35889a450000000001'), new ObjectId('50478c35889a450000000002')]

Post.findOne({ _id: post_id })
     .select({ comments: { $elemMatch: {$in: ids }}})
     .exec(function (err, doc) {
         console.log(doc.comments); // empty []
         done(err);
});
@skotchio
skotchio commented Sep 6, 2012

Thank you for the answer but do you plan to cast a field projections in a future because I get an array of ids from a client I would like to avoid a using loops?

@aheckmann
Collaborator

yes

On Sep 5, 2012, at 8:24 PM, Lary notifications@github.com wrote:

Thank you for the answer but do you plan to cast a field projections in a future because I get an array of ids from a client I would like to avoid a using loops?


Reply to this email directly or view it on GitHub.

@aheckmann aheckmann added a commit that closed this issue Sep 10, 2012
@aheckmann aheckmann fixed; $elemMatch+$in with field selection
mongodb 2.2 support

closes #1091
9cc448b
@aheckmann aheckmann closed this in 9cc448b Sep 10, 2012
@aheckmann aheckmann added a commit that referenced this issue Sep 10, 2012
@aheckmann aheckmann fixed; $elemMatch+$in with field selection
mongodb 2.2 support

closes #1091
1258022
@aheckmann
Collaborator

released in 3.1.2

@aheckmann
Collaborator

and 2.8.3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment