从Mongoose中的subdoc ID中查找父Doc

时间:2017-02-22 17:54:56

标签: node.js mongodb express mongoose

我有subdoc Id,我需要使用parent DocMongoose返回MongoDB。我在这里阅读:MongoDB: How to find by subdocument ID?我应该能够使用Polls.find({'options': id},但它返回任何空数组而不是相应的文档。

模式

var Polls = new Schema({
    name: String,
    options: [{
        name: String,
        count: Number
    }]
}

示例投票

{
"_id": {
    "$oid": "58ac963a8a84500de89c1080"
},
"name": "Here is one Poll",
"options": [
    {
        "name": "This is the first one",
        "count": 0,
        "_id": {
            "$oid": "58ac963a8a84500de89c1083"
        }
    },
    {
        "name": "Second One",
        "count": 0,
        "_id": {
            "$oid": "58ac963a8a84500de89c1082"
        }
    }
],
"__v": 0
}

1 个答案:

答案 0 :(得分:1)

我认为你错了。

试试这个:

Polls.find({'options._id': id},function(err,result){
    //result will be an array of matched document
    //result[i]._id will give you the parent id.
    //if there is only one such document, you can try : result[0]._id
});