Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

find multiple documents by the same objectID

find multiple documents by the same objectID

Problem

I have a documents with the following structure:

the model:

var relationID = Schema({
    _id: {type: Schema.Types.ObjectId}
});

    var schemaName = Schema({   
    relations:[relationID],   
    meta: {},    
    modificationDate: {type: Date, "default": Date.now}});

doc 1:

doc:  { 
_id: 52cdb245f5116f8567000004

relations: 
   [{ 
      _id: 52cd9930a22c865a44000006
   }]
} 

doc 2:

doc:  { 
    _id: 52d01bf303aaa8f473000005

    relations: 
       [{ 
          _id: 52cd9930a22c865a44000006
       }]
} 

Both docs have the same relations id. I want to select them with:

exports.detail = function (req, res) {
    var condition, fields, options;
    condition = {relationsID: { $in: [ "52cd9930a22c865a44000006"]  } }

        fields = {},
        options = {'createdAt': -1};

    transactions
        .find(condition, fields)
        .exec(function (err, doc){
            var retObj = {
                meta: {"action": "list",'timestamp': new Date()},
                doc: doc[0],
                err: err
            };
            return res.send(retObj);
        })
}

it doesn't work. How can i select both docs?

Thanks!

Problem courtesy of: Pmpha

Solution

All you need is:

var condition = {'relations._id': '52cd9930a22c865a44000006'};

Mongodb will interpret that intuitively for an array of objects. You do not need the $in operator. Mongodb knows when it finds a document where .relations is an array, to look through the array for a subdocument with the matching ._id.

Solution courtesy of: Peter Lyons

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

find multiple documents by the same objectID

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×