使用Mongoose JS获取文档的指针值数组,并展开return

时间:2013-06-09 04:20:04

标签: node.js mongodb mongoose

我要做的是以下内容。

我有可以存在多个文档的对象,虽然我不确定这是否是最佳实践,但我使用它们的ObjectId作为指针。

文件A

{
"_id": {
    "$oid": "51a02dade4b02780aeee5ab7"
},
"title": "My Document A",
"artifacts": [
    "51a81d8ee4b084336fea2d33",
    "asdfsdfe4b084336fea2d33"
]

}

文件B

{
"_id": {
    "$oid": "51a02dade4b02780aeee5ab7"
},
"title": "My Document A",
"artifacts": [
    "51a81d8ee4b084336fea2d33",
    "123454b084336fea2d33"
]

}

单个神器看起来像。如果此工件发生更改,则无需更新其所在的文档:

{
    "_id": {
        "$oid": "51a81d8ee4b084336fea2d33"
    },
    "title": "Artifact A",
    "media": {
        "player": "video",
        "source": "http://www.youtube.com/watch?v=12334456"
    }
}

我想做的是获取一个扩展的列表,其中列出了数组中doc A或doc B中显示的所有工件:

[{
        "_id": {
            "$oid": "51a81d8ee4b084336fea2d33"
        },
        "title": "Artifact A",
        "media": {
            "player": "video",
            "source": "http://www.youtube.com/watch?v=12334456"
        }
    },
{
        "_id": {
            "$oid": "123455e4b084336fea2d33"
        },
        "title": "Artifact B",
        "media": {
            "player": "video",
            "source": "http://www.youtube.com/watch?v=12334456"
        }
    }]

我过去的做法是从客户端发布一个ID列表,然后使用

{_id: { $in: userQuestArray} } 

但如果我经常从客户端发回节点,那似乎有点低效。特别是如果我发布的数组长达数百个项目。

1 个答案:

答案 0 :(得分:1)

Mongoose为您提供了一个功能人群,与您正在寻找的http://mongoosejs.com/docs/populate.html完全相同。在您的情况下,您需要做的是

var mongoose = require('mongoose')
, Schema = mongoose.Schema

var tempSchema = Schema({    
title    : String,   
artifacts : [{ type: Schema.Types.ObjectId, ref: 'Artifacts' }]
});

var artifactsSchema = Schema({    
title    : String,   
media : { player: String, source: String, }
});

var tempModel  = mongoose.model('Temp', tempSchema);
var artifactsModel = mongoose.model('Artifacts', artifactsSchema);

现在,无论何时创建工件文档,您都需要在相应的临时文件数组中推送它,如mongoose文档中所示。你可以像那样重审它

tempModel
    .find(query)
    .populate('artifacts')
    .exec(function (err, results) {
        if (err)
            console.log(err);

        console.log(results);
    })
 //results contains data in form shown below
 [{
   "_id": {
     "$oid": "51a02dade4b02780aeee5ab7"
    },
   "title": "My Document A",
   "artifacts": [{
    "_id": {
        "$oid": "51a81d8ee4b084336fea2d33"
    },
    "title": "Artifact A",
    "media": {
        "player": "video",
        "source": "http://www.youtube.com/watch?v=12334456"
    }
   },
   {
    "_id": {
        "$oid": "123455e4b084336fea2d33"
    },
    "title": "Artifact B",
    "media": {
        "player": "video",
        "source": "http://www.youtube.com/watch?v=12334456"
    }
   }]
 }]