Mongoose填充特定的数组实例

时间:2015-02-08 01:30:01

标签: node.js mongodb mongoose mongodb-query mongoose-populate

我尝试了很多组合没有成功,所以需要你的帮助。

考虑您的文档架构和版本

var VersionSchema = mongoose.createSchema("version", {
    version:  { type: Number},
    metadata: { type: Schema.Types.ObjectId, ref: 'Metadata' }
});

var documentSchema = mongoose.createSchema("document", {
    projectId: { type: Schema.Types.ObjectId},
    versions:  [VersionSchema],
    deleted:   { type: Boolean, default: false}
});

数据将如下所示

{
    _id: a58107da0dc3da020998787c,
    projectId: 09434766ab47c29609972596,
    deleted: false,
    versions: [
        { _id: 9ac67dc1b84df1ff09988ea1, version: 1, Metadata: [Object] },
        { _id: 9ac67dc1b84df1ff09988ea2, version: 2, Metadata: [Object] }
    ]
}

我想只填充最新版本的文档..版本2 ..并非所有子版本..

我尝试过但需要帮助..

Document.findOne({ projectId: projectId }, function(error, document) {
    var options = [{
        path: 'versions.Metadata,
        model: Metadata
            //,
            //match: { version: 2 }
    }];
    Version.populate(document, options, function(err, doc) {
        deferred.resolve(doc);
    });
});

1 个答案:

答案 0 :(得分:0)

Document.findOne({ projectId: projectId }, function(error, document) {
    var options = [{
                    path: 'versions.Metadata,
                    model: Metadata
                   }];
    var version = document.versions[document.versions.length - 1];
    Version.populate(version, options, function(err, updatedVer) {
         deferred.resolve(updatedVer);
        });
  });