通过相同的objectID查找多个文档

时间:2014-01-11 00:28:53

标签: node.js mongodb angularjs mongoose

我有一个具有以下结构的文件:

模特:

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
       }]
} 

两个文档都具有相同的关系ID。我想用:

选择它们
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);
        })
}

它不起作用。我如何选择两个文档?

谢谢!

1 个答案:

答案 0 :(得分:1)

您只需要:

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

Mongodb将直观地解释对象数组。您不需要$in运算符。 Mongodb知道何时找到.relations是一个数组的文档,在数组中查找匹配._id的子文档。