0

我想要做的是以下。

我有可以存在于多个文档中的对象,虽然我不确定这是否是最佳实践,但我使用它们的 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"
    }
}

我想做的是获取一个扩展列表,其中包含文档 A 或文档 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} } 

但如果我不断地从客户端发回节点,它似乎有点低效。特别是如果我发布的数组有数百个项目。

4

1 回答 1

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);

现在,每当创建工件文档时,您都需要将其推送到相应的临时文档工件数组中,如猫鼬文档中所示。你可以像这样检索它

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"
    }
   }]
 }]
于 2013-06-11T07:48:04.963 回答